默認情況下,BeautifulSoup
使用minimal
輸出格式化程序並轉換HTML實體。
的解決方案是設置爲從BS源(PageElement
文檔字符串)輸出格式化到None
,報價:
# 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>
希望有所幫助。
你是如何打印輸出? – shaktimaan