fat*_*sma 7 html python beautifulsoup html-parsing
我正在尝试将“ ”添加到 Beautifulsoup 标签中。BS 将 转换tag.string为\ 而不是 . 这一定是一些编码问题,但我无法弄清楚。
请注意:忽略后面的“\”字符。我必须添加它,以便 stackoverflow 能够正确格式化我的问题。
import bs4 as Beautifulsoup
html = "<td><span></span></td>"
soup = Beautifulsoup(html)
tag = soup.find("td")
tag.string = " "
Run Code Online (Sandbox Code Playgroud)
当前输出为 html = "\ "
有任何想法吗?
默认情况下BeautifulSoup使用minimal输出格式化程序并转换 HTML 实体。
解决方案是将输出格式化程序设置为None,引用 BS 源(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".
Run Code Online (Sandbox Code Playgroud)
例子:
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)
Run Code Online (Sandbox Code Playgroud)
印刷:
<td>
<span>
</span>
</td>
Run Code Online (Sandbox Code Playgroud)
希望有帮助。