BeautifulSoup找不到正确解析的元素

2024-09-29 23:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用BeautifulSoup来解析一堆可能非常脏的HTML文档。我偶然发现了一件很奇怪的事。在

HTML来自此页面:http://www.wvdnr.gov/

它包含多个错误,比如多个<html></html><title><head>之外,等等。。。在

然而,html5lib通常即使在这些情况下也能很好地工作。事实上,当我这样做的时候:

soup = BeautifulSoup(document, "html5lib")

我打印soup,我看到了以下输出:http://pastebin.com/8BKapx88

它包含很多<a>标记。在

但是,当我做soup.find_all("a")时,我得到一个空列表。使用lxml我也得到同样的结果。在

那么:以前有人碰到过这个问题吗?怎么回事?如何获取html5lib找到但没有返回find_all的链接?在


Tags: 文档httptitlehtmlwww错误页面all
2条回答

即使正确答案是“使用另一个解析器”(谢谢@alecxe),我还有另一个解决方法。出于某种原因,这也很有效:

soup = BeautifulSoup(document, "html5lib")
soup = BeautifulSoup(soup.prettify(), "html5lib")
print soup.find_all('a')

它返回相同的链接列表:

^{pr2}$

当要解析格式不好且复杂的HTML时,the parser choice非常重要:

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.

html.parser为我工作:

from bs4 import BeautifulSoup
import requests

document = requests.get('http://www.wvdnr.gov/').content
soup = BeautifulSoup(document, "html.parser")
print soup.find_all('a')

演示:

^{pr2}$

另请参见:

相关问题 更多 >

    热门问题