2014-05-06 24 views
0

我想解析this site和我無法理解的原因,什麼都沒有發生。Beautifulsoup不工作在一個特定的網站

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. 

此網站是在巴西里約熱內盧的真實狀態廣告。我無法找到任何可能阻止Beautifulsoup工作的html源代碼。它的大小?

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

+0

相同的代碼對我來說完美地工作,它顯示560 ... – fasouto

+0

使用下面的提示,我的環境只適用於'html.parser'配置。 – srodriguex

回答

5

這是因爲你讓BeautifulSoup選擇最合適解析器你。而且,這實際上取決於你的python環境中安裝了哪些模塊。

按照documentation

的第一個參數的構造函數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 

你會指定一個分析器,可以處理這個特定頁面的解析解,你可能需要安裝lxmlhtml5lib

另請參閱:Differences between parsers

+0

有趣。我認爲解析器之間的差異只是速度。我認爲默認的解析器是最容忍的呢? – dilbert

+0

@dilbert如果你在談論'html.parser',那麼它取決於python的版本,在2.7的情況下,它比以前更寬容。 'html5lib'應該是最寬鬆的,但是,正如你所看到的,它不能正確解析頁面。 – alecxe

+0

@alecxe我已經嘗試過lxml和html5lib解析器,並得到相同的結果,什麼也沒有。但與我不知道的html.parser,它運行良好。這可能是Entreprene分銷問題的原因嗎?無論如何,和html.parser一樣,我可以繼續前進。謝謝! – srodriguex

0

某處有問題,你的環境,這裏是輸出我得到:

>>> url = 'http://www.zap.com.br/imoveis/rio-de-janeiro+rio-de-janeiro/apartamento-padrao/venda/' 
>>> from bs4 import BeautifulSoup 
>>> import urllib2 
>>> response = urllib2.urlopen(url).read() 
>>> doc = BeautifulSoup(response) 
>>> divs = doc.findAll('div') 
>>> print len(divs) # prints 0. 
558 
+0

你會建議我尋找什麼?我不知道我的環境有什麼問題。 – srodriguex

相關問題