BeautifulSoup4 缺少标签

BeautifulSoup4 missing tags

我在 Anaconda 的发行版中使用 BeautifulSoup 4 作为 bs4。如果我错了请纠正我——我理解 BeautifulSoup 是用于将格式错误的 HTML 转换为格式正确的库。但是,当我将 HTML 分配给它的构造函数时,我丢失了一半以上的字符。不应该只是修复 HTML 而不是清理它吗?在 docs 中没有很好地描述。

这是代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(html)

其中 html 是 Google 主页的 HTML。

编辑:

会不会是我通过 str(soup) 检索 HTML 字符串的方式?

首先,确保你看到 html 中的这些 "missing tags" 进入 BeautifulSoup 进行解析。问题可能不在于 BeautifulSoup 如何解析 HTML,而在于您如何检索要解析的 HTML 数据。

我怀疑,您正在通过 urllib2requests 下载 google 主页,并将您在 str(soup) 中看到的内容与您在真实浏览器中看到的内容进行比较。如果是这种情况,那么 你不能比较两者 ,因为 urllib2requests 都不是浏览器,不能执行 javascript 或操作 DOM页面加载后,或者进行异步请求。 urllib2requests 基本上是初始 HTML 页面 "without a dynamic part".


如果问题仍然在于 BeautifulSoup 如何解析 HTML...

正如文档中明确指出的那样,行为取决于哪个解析器 BeautifulSoup 会选择在后台使用:

There are also differences between HTML parsers. If you give Beautiful Soup a perfectly-formed HTML document, these differences won’t matter. One parser will be faster than another, but they’ll all give you a data structure that looks exactly like the original HTML document. But if the document is not perfectly-formed, different parsers will give different results.

参见 Installing a parser and Specifying the parser to use

由于您没有明确指定解析器,因此应用以下规则:

If you don’t specify anything, you’ll get the best HTML parser that’s installed. Beautiful Soup ranks lxml’s parser as being the best, then html5lib’s, then Python’s built-in parser.

另见 Differences between parsers


换句话说,尝试使用不同的解析器来解决问题,看看结果会有什么不同:

soup = BeautifulSoup(html, 'lxml')
soup = BeautifulSoup(html, 'html5lib')
soup = BeautifulSoup(html, 'html.parser')