【问题标题】:Beautifulsoup lost nodesBeautifulsoup 丢失节点
【发布时间】:2013-05-01 10:53:28
【问题描述】:

我正在使用 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

【问题讨论】:

  • 尝试不同的解析器;提要中的 HTML 已损坏,不同的解析器处理不同。

标签: python beautifulsoup html5lib


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-12-26
    • 1970-01-01
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-22
    相关资源
    最近更新 更多