Beautifulsoup不在特定网站上工作

sro*_*uex 0 html python beautifulsoup html-parsing python-2.7

我正在尝试解析这个网站,由于我无法理解的原因,没有任何事情发生.

url = 'http://www.zap.com.br/imoveis/rio-de-janeiro+rio-de-janeiro/apartamento-padrao/venda/'
response = urllib2.urlopen(url).read()
doc = BeautifulSoup(response)
divs = doc.findAll('div')
print len(divs) # prints 0.
Run Code Online (Sandbox Code Playgroud)

该网站是巴西里约热内卢的一个真实广告.我在html源代码中找不到任何可以阻止Beautifulsoup工作的东西.这是大小吗?

我正在使用Enthought Canopy Python 2.7.6,IPython Notebook 2.0,Beautifulsoup 4.3.2.

ale*_*cxe 5

这是因为您要BeautifulSoup为您选择最合适的解析器.而且,这实际上取决于python环境中安装的模块.

根据文件:

BeautifulSoup构造函数的第一个参数是一个字符串或一个打开的文件句柄 - 您想要解析的标记.第二个参数是你如何解析标记.

如果您没有指定任何内容,您将获得已安装的最佳HTML解析器.Beautiful Soup将lxml的解析器列为最佳,然后是html5lib,然后是Python的内置解析器.

所以,不同的解析器 - 不同的结果:

>>> from bs4 import BeautifulSoup
>>> url = 'http://www.zap.com.br/imoveis/rio-de-janeiro+rio-de-janeiro/apartamento-padrao/venda/'
>>> import urllib2
>>> response = urllib2.urlopen(url).read()
>>> len(BeautifulSoup(response, 'lxml').find_all('div'))
558
>>> len(BeautifulSoup(response, 'html.parser').find_all('div'))
558
>>> len(BeautifulSoup(response, 'html5lib').find_all('div'))
0
Run Code Online (Sandbox Code Playgroud)

您的解决方案是指定一个可以处理此特定页面解析的解析器,您可能需要安装lxmlhtml5lib.

另请参阅:解析器之间的差异.