我使用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
的链接?在
即使正确答案是“使用另一个解析器”(谢谢@alecxe),我还有另一个解决方法。出于某种原因,这也很有效:
它返回相同的链接列表:
^{pr2}$当要解析格式不好且复杂的HTML时,the parser choice非常重要:
html.parser
为我工作:演示:
^{pr2}$另请参见:
相关问题 更多 >
编程相关推荐