如何在BeautifulSoup标签中插入空白字符( )?
我正在尝试在BeautifulSoup标签中添加一个' '。但是,BS把tag.string
转换成了\ 
,而不是 
。这肯定是编码的问题,但我搞不清楚怎么回事。
请注意:忽略反斜杠'\'字符。我必须加上它,这样stackoverflow才能正确格式化我的问题。
import bs4 as Beautifulsoup
html = "<td><span></span></td>"
soup = Beautifulsoup(html)
tag = soup.find("td")
tag.string = " "
当前输出是 html = "\&ampnbsp;"
有什么想法吗?
3 个回答
0
你需要添加一个不换行的空格,这个在Python中可以用"\xa0"来表示:
soup = BeautifulSoup("", "html5lib") # html5lib will add html and body tags by default
soup.body.string = "\xa0" # uncode non-breaking space
soup.encode("ascii") # to see final html in ascii encoding
结果:
b'<html><head></head><body> </body></html>'
4
虽然alecxe的回答可以用,但前提是你不介意使用formatter=None
。不过如果你想在某些HTML中插入一个
,而且还希望它有特定的格式(比如"html5"
或"html"
),那这个方法就不太合适了。
我发现Muposat的建议,使用"\xa0"
,对我来说效果很好。
所以,我对alecxe的回答做了些调整:
from bs4 import BeautifulSoup
html = "<td><span></span></td>"
soup = BeautifulSoup(html, "html.parser")
tag = soup.find("span")
tag.string = "\xa0"
print soup.prettify(formatter="html5")
输出结果是:
<td>
<span>
</span>
</td>
这是在使用python 3.7。
5
默认情况下,BeautifulSoup
使用的是minimal
输出格式,这种格式会把HTML中的特殊字符转换成对应的实体。
解决这个问题的方法是把输出格式设置为None
,以下是来自BeautifulSoup源代码中的一段引用(PageElement
的文档说明):
# There are five possible values for the "formatter" argument passed in
# to methods like encode() and prettify():
#
# "html" - All Unicode characters with corresponding HTML entities
# are converted to those entities on output.
# "minimal" - Bare ampersands and angle brackets are converted to
# XML entities: & < >
# None - The null formatter. Unicode characters are never
# converted to entities. This is not recommended, but it's
# faster than "minimal".
示例:
from bs4 import BeautifulSoup
html = "<td><span></span></td>"
soup = BeautifulSoup(html, 'html.parser')
tag = soup.find("span")
tag.string = ' '
print soup.prettify(formatter=None)
输出结果是:
<td>
<span>
</span>
</td>
希望这能帮到你。