python - 使用 BeautifulSoup 解析 HTML 时缺少特殊字符和标签

标签 python python-3.x parsing beautifulsoup html-parsing

我正在尝试使用带有 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 %&amp;#@???»</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/

相关文章:

python - 如何通过企业代理访问 App Engine?

python-3.x - 使用 pyinstaller 将 Exe 转换为 python?

c - Yacc问题: Make Data available in next Non Terminal

java - 在 joda time 中使用 parseDateTime 时休息 1 天

python 2.6 : parallel parsing with urllib2

python - 从十六进制转换为二进制而不丢失前导 0 的 python

python - 编写一个自定义 Django BaseCommand 类来记录命令详细信息

python - Django - 使用通用 View 找不到 URL

python - 在 Python 3.3 中解方程

python - 为什么使用 lambda 与 1 行函数声明?