我正在尝试使用带有 Python 的 BeautifulSoup
来解析 HTML 文档。
但它会停止解析特殊字符,如下所示:
from bs4 import BeautifulSoup
doc = '''
<html>
<body>
<div>And I said «What the %&#@???»</div>
<div>some other text</div>
</body>
</html>'''
soup = BeautifulSoup(doc, 'html.parser')
print(soup)
此代码应输出整个文档。相反,它只打印
<html>
<body>
<div>And I said «What the %</div></body></html>
文档的其余部分显然已丢失。它被 ''
组合停止。
问题是,如何设置 BS 或预处理文档,以避免此类问题,同时丢失尽可能少的文本(可能是信息性的)?
我在 Windows 10 上使用 4.6.0 版的 bs4 和 Python 3.6.1。
更新。 soup.prettify()
方法不起作用,因为 soup
已经坏了。
最佳答案
您需要在 BeautifulSoup
对象中使用“html5lib”而不是“html.parser”作为解析器。例如:
from bs4 import BeautifulSoup
doc = '''
<html>
<body>
<div>And I said «What the %&#@???»</div>
<div>some other text</div>
</body>
</html>'''
soup = BeautifulSoup(doc, 'html5lib')
# different parser ^
现在,如果您要打印 soup
,它将显示您想要的字符串:
>>> print(soup)
<html><head></head><body>
<div>And I said «What the %&#@???»</div>
<div>some other text</div>
</body></html>
来自Difference Between Parsers文档:
Unlike
html5lib
,html.parser
makes no attempt to create a well-formed HTML document by adding a tag. Unlike lxml, it doesn’t even bother to add an tag.
关于python - 使用 BeautifulSoup 解析 HTML 时缺少特殊字符和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48125988/