Beautiful Soup 4 find_all找不到Beautiful Soup 3找到的链接
问题内容:
我注意到一个非常烦人的错误: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'
问题答案:
您已经lxml
安装了,这意味着BeautifulSoup 4将在标准库选项上使用 该 解析器html.parser
。
您可以将lxml升级到3.2.1(对我来说,这将为您的测试页返回1701个结果);lxml本身会使用libxml2
,libxslt
在这里也可能要怪。您可能还必须升级
这些
。请参阅lxml要求页面;当前建议使用libxml2
2.7.8或更高版本。
或在解析汤时明确指定其他解析器:
s4 = bs4.BeautifulSoup(r.text, 'html.parser')