python - 如何在 Beautifulsoup 标签中插入空格 (&nbsp)?

标签 python html html-parsing beautifulsoup

我正在尝试将“ ”添加到 Beautifulsoup 标签中。 BS 将 tag.string 转换为 \  而不是  。一定是编码问题,但我想不通。

请注意:忽略后面的“\”字符。我必须添加它,这样 stackoverflow 才能正确格式化我的问题。

import bs4 as Beautifulsoup

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

当前输出为html = "\ "

有什么想法吗?

最佳答案

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

解决方案是将输出格式化程序设置为None,引用自 BS source (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>

希望对您有所帮助。

关于python - 如何在 Beautifulsoup 标签中插入空格 (&nbsp)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187049/

相关文章:

python - 使用 python 和 gtk 3 将 gtk 应用程序主题更改为默认主题

python - 以敏捷/BDD 方式在 Django 中使用 Doctests 的示例

jquery - 如何隐藏 HTML 中溢出文本的单词?

python - 我如何循环研究并搜索下一个数据

python - 使用代理与 phantomjs (selenium webdriver)

python - 从命令行构建列表列表

html - Flexbox 元素不会在浏览器窗口调整大小时重新排序,但会在响应模式下重新排序

php - 在用户下载之前调整图像大小?

node.js - 用node.js解析奇怪的html

python - 使用 Beautiful Soup 将 CSS 属性转换为单个 HTML 属性?