python - Beautifulsoup、Python 和 HTML 自动页面截断?

标签 python beautifulsoup

我正在使用 Python 和 BeautifulSoup 来解析 HTML 页面。不幸的是,对于某些页面(> 400K),BeatifulSoup 正在截断 HTML 内容。

我使用以下代码获取“div”的集合:

findSet = SoupStrainer('div')
set = BeautifulSoup(htmlSource, parseOnlyThese=findSet)
for it in set:
    print it

在某个时刻,输出看起来像:

正确的字符串,正确的字符串,不完整/截断的字符串(“So,I”)

不过,htmlSource 包含字符串“So, I am bored”,以及许多其他字符串。另外,我想提一下,当我 prettify() 树时,我看到 HTML 源代码被截断了。

您知道我该如何解决这个问题吗?

谢谢!

最佳答案

尝试使用 lxml.html .它是一个更快、更好的 html 解析器,并且比最新的 BeautifulSoup 更好地处理损坏的 html。它适用于您的示例页面,解析整个页面。

import lxml.html

doc = lxml.html.parse('http://voinici.ceata.org/~sana/test.html')
print len(doc.findall('//div'))

上面的代码返回 131 个 div。

关于python - Beautifulsoup、Python 和 HTML 自动页面截断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3704821/

相关文章:

python - 使用 Python SSL 的匿名 DH 连接

html - 使用 Beautifulsoup 提取下一个和不同标签的内容

Python Mechanize HTTP 错误 403 : request disallowed by robots. txt

python - 如何在 python 中使用 Selenium 和 Beautifulsoup 解析网站?

python - 查找 XML 标记值并选择包含所请求标记值的父级

python - 如何在多维 numpy 数组的多个轴上找到最大值?

python - 更改 lxml 中的元素命名空间

python - 用soup.select在美汤中选二胎?

python - 将 Python 移植到嵌入式系统

python - 矩阵和数组的 NumPy 点积