美丽的汤4 find_all没有找到美丽的汤3找到的链接

时间:2013-07-17 11:40:57

标签: python web web-scraping beautifulsoup

我注意到一个非常烦人的错误:BeautifulSoup4(包:bs4)经常找到比以前版本更少的标签(包:BeautifulSoup)。

以下是该问题的可重现实例:

import requests
import bs4
import BeautifulSoup

r = requests.get('http://wordpress.org/download/release-archive/')
s4 = bs4.BeautifulSoup(r.text)
s3 = BeautifulSoup.BeautifulSoup(r.text)

print 'With BeautifulSoup 4 : {}'.format(len(s4.findAll('a')))
print 'With BeautifulSoup 3 : {}'.format(len(s3.findAll('a')))

输出:

With BeautifulSoup 4 : 557
With BeautifulSoup 3 : 1701

您可以看到差异并不小。

以下是模块的确切版本,以防有人想知道:

In [20]: bs4.__version__
Out[20]: '4.2.1'

In [21]: BeautifulSoup.__version__
Out[21]: '3.2.1'

1 个答案:

答案 0 :(得分:9)

您已安装lxml,这意味着BeautifulSoup 4将使用 解析器而不是标准库html.parser选项。

您可以将lxml升级到3.2.1(对我来说,为您的测试页返回1701个结果); lxml本身使用libxml2libxslt,这可能也应该归咎于此。您可能还必须升级那些。见lxml requirements page;目前建议使用libxml2 2.7.8或更新版本。

或者在解析汤时显式指定另一个解析器:

s4 = bs4.BeautifulSoup(r.text, 'html.parser')
相关问题