2013-05-01 115 views
1

我正在使用Python和Beautifulsoup来解析HTML数据并从RSS-Feeds中获取p-tags。但是,有些URL会导致问题,因为解析的汤对象不包含文档的所有节点。Beautifulsoup丢失节点

比如我试图解析http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm

但比较网页源代码解析的对象之后,我注意到,ul class="nextgen-left"后,所有的节点都不见了。

这是我如何解析文件:

from bs4 import BeautifulSoup as bs 

url = 'http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm' 

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
request = urllib2.Request(url) 

response = opener.open(request) 

soup = bs(response,'lxml')   
print soup 
+2

尝试使用其他解析器; Feed中的HTML被破坏,不同的解析器处理的方式不同。 – 2013-05-01 10:56:49

回答

6

输入HTML是不太符合的,所以你必须在这里使用一个不同的解析器。 html5lib解析器正确处理此页:

>>> import requests 
>>> from bs4 import BeautifulSoup 
>>> r = requests.get('http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm') 
>>> soup = BeautifulSoup(r.text, 'lxml') 
>>> soup.find('div', id='story-body') is not None 
False 
>>> soup = BeautifulSoup(r.text, 'html5') 
>>> soup.find('div', id='story-body') is not None 
True