如何在Beautifulsoup标签中插入空格()?

时间:2014-03-05 02:03:44

标签: python html html-parsing beautifulsoup

我正在尝试将一个'& nbsp'添加到Beautifulsoup标签中。 BS将tag.string转换为\&ampamp;nbsp;而不是&nbsp。它必须是一些编码问题,但我无法弄明白。

请注意:忽略后面的'\'字符。我必须添加它,所以stackoverflow会正确地格式化我的问题。

import bs4 as Beautifulsoup

html = "<td><span></span></td>"
soup = Beautifulsoup(html)
tag = soup.find("td")
tag.string = "&nbsp;"

当前输出为html =“\&amp; amp; nbsp;”

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

尽管如果您不介意使用formatter=None,alecxe的the answer也可以使用,但是如果您想将&nbsp;插入您要执行的某些HTML中,则没有用 em>希望具有特定的格式(例如"html5""html")。

我发现Muposat使用"\xa0"的{​​{3}}对我有用。

因此,要适应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>
  &nbsp;
 </span>
</td>

这是使用python 3.7。

答案 1 :(得分:0)

默认情况下,BeautifulSoup使用minimal输出格式化程序并转换HTML实体。

解决方法是将输出格式化程序设置为None,引用BS源代码(PageElement docstring):

# 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: &amp; &lt; &gt;
# 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 = '&nbsp;'

print soup.prettify(formatter=None)

打印:

<td>
 <span>
  &nbsp;
 </span>
</td>

希望有所帮助。

答案 2 :(得分:-1)

您需要添加unicode非中断空间,可以表示为&#34; \ xa0&#34;在python:

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>&#160;</body></html>'