Skip to main content
 首页 » 编程设计

python之Beautifulsoup 丢失节点

2025年05月04日17虾米姐

我正在使用 Python 和 Beautifulsoup 来解析 HTML 数据并从 RSS 提要中获取 p 标签。但是,一些 url 会导致问题,因为解析的 soup-object 不包括文档的所有节点。

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

请您参考如下方法:

输入的 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