【问题标题】:How to insert a blank space(&nbsp) into a Beautifulsoup tag?如何在 Beautifulsoup 标签中插入空格(&nbsp)?
【发布时间】:2014-04-06 21:05:58
【问题描述】:

我正在尝试将“&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 = "\&nbsp;"

有什么想法吗?

【问题讨论】:

  • 如何打印输出?

标签: python html html-parsing beautifulsoup


【解决方案1】:

默认情况下 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】:

虽然如果您不介意使用formatter=None,alecxe 的the answer 可以工作,但如果您想将&amp;nbsp; 插入到您希望拥有特定格式(如"html5" 或"html")。

我发现 Muposat 的 suggestion 使用 "\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>
  &nbsp;
 </span>
</td>

这是使用 python 3.7。

【讨论】:

    【解决方案3】:

    需要添加unicode不间断空格,在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>&#160;</body></html>'
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 2019-10-25
      • 1970-01-01
      • 2015-09-17
      • 2020-10-05
      • 1970-01-01
      相关资源
      最近更新 更多