hal*_*ngs 0 python beautifulsoup web-scraping web
我注意到一个非常烦人的错误: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')))
Run Code Online (Sandbox Code Playgroud)
输出:
With BeautifulSoup 4 : 557
With BeautifulSoup 3 : 1701
Run Code Online (Sandbox Code Playgroud)
你可以看到,差异并不小.
以下是模块的确切版本,以防有人想知道:
In [20]: bs4.__version__
Out[20]: '4.2.1'
In [21]: BeautifulSoup.__version__
Out[21]: '3.2.1'
Run Code Online (Sandbox Code Playgroud)
您已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')
Run Code Online (Sandbox Code Playgroud)