提取元素并插入空格

21 投票
3 回答
5874 浏览
提问于 2025-04-16 20:12

我正在用Python的BeautifulSoup库解析HTML。

我不知道在提取文本元素时怎么插入空格。

这是我的代码:

import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>this<b>is</b>example</html>')
print soup.text

然后输出是:

thisisexample

但我想把它改成这样:

yes is example

我该怎么插入空格呢?

3 个回答

2

有时候你可能还想使用带有去除空白的选项。

bs = BeautifulSoup("<html>this<b>is  </b>example</html>")
print(bs.get_text())  # thisis  example
print(bs.get_text(separator=" "))  # this is   example
print(bs.get_text(separator=" ", strip=True))  # this is example
2

如果你使用的BeautifulSoup版本没有getText这个功能,你可以这样做:

In [26]: ' '.join(soup.findAll(text=True))
Out[26]: u'this is example'
48

使用 getText 来代替:

import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>this<b>is</b>example</html>')

print soup.getText(separator=u' ')
# u'this is example'

撰写回答