2

我的代码:

html = "<tag>&nbsp;</tag>"
from bs4 import BeautifulSoup
print BeautifulSoup(html).renderContents()

输出:

<tag> &lt;/tag>

期望的输出:

<tag>&nbsp;</tag>

BeautifulSoup 似乎用一个表示相同含义的 unicode 字符替换了我的破坏空间 html 转义。但这并不能一直贯穿我的系统,最终成为一个不间断的空间,因此没有做我想做的事。有没有办法告诉 BeautifulSoup 不要那样做?

4

1 回答 1

6

使用encode_contents代替renderContents,或encodeprettify。它们都支持formatter参数,并'html'作为格式化程序传递:

html = "<tag>&nbsp;</tag>"
from bs4 import BeautifulSoup
print BeautifulSoup(html).encode_contents(formatter='html')

产生:

<tag>&nbsp;</tag>
于 2013-06-20T22:56:16.800 回答