Beautifulsoup失去了节点

时间:2013-05-01 10:53:29

标签: python beautifulsoup html5lib

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

例如,我尝试解析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

1 个答案:

答案 0 :(得分: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
相关问题