【问题标题】:Parsing XML RSS feed byte stream for <item> tag为 <item> 标签解析 XML RSS 提要字节流
【发布时间】:2013-01-23 11:48:28
【问题描述】:

我正在尝试为元素“”的第一个实例解析 RSS 提要。

def pageReader(url):
try:
    readPage = urllib2.urlopen(url)
except urllib2.URLError, e:
#   print 'We failed to reach a server.'
#   print 'Reason: ', e.reason
    return 404  
except urllib2.HTTPError, e:
#   print('The server couldn\'t fulfill the request.')
#   print('Error code: ', e.code)   
    return 404  
else:
    outputPage = readPage.read()        
return outputPage

假设传递的参数是正确的。该函数返回一个 str 对象,其值只是一个完整的 rss 提要 - 我已经确认了类型:

a = isinstance(value, str)
if not a:
   return -1

所以,函数调用返回了整个 rss 提要,这就是我碰壁的地方 - 我尝试使用 BeautifulSoup、lxml 和各种其他库解析提要,但没有成功(我有 一些 BeautifulSoup 取得了成功,但它无法从父元素中提取某些子元素,例如 . 我正准备求助于编写自己的解析器,但我想知道是否有人有任何建议。

要重新创建我的错误,只需使用类似于以下参数的参数调用上述函数:

http://www.cert.org/nav/cert_announcements.rss

你会看到我正在尝试返回第一个孩子。

<item>
<title>New Blog Entry: Common Sense Guide to Mitigating Insider Threats - Best Practice 16 (of 19)</title>
<link>http://www.cert.org/blogs/insider_threat/2013/02/common_sense_guide_to_mitigating_insider_threats_-_best_practice_16_of_19.html</link>
<description>This sixteenth of 19 blog posts about the fourth edition of the Common   Sense Guide to Mitigating Insider Threats describes Practice 16: Develop a formalized insider threat program.</description>
<pubDate>Wed, 06 Feb 2013 06:38:07 -0500</pubDate>
</item>

正如我所说,BeautifulSoup 无法找到对我的应用至关重要的 pubDate 和 Link。

任何建议将不胜感激。

【问题讨论】:

    标签: python xml parsing rss beautifulsoup


    【解决方案1】:

    我使用 BeautifulStoneSoup 并像这样传递小写标签取得了一些成功:

    from BeautifulSoup import BeautifulStoneSoup
    xml = '<item><title>New Blog Entry: Common Sense Guide to Mitigating Insider Threats - Best Practice 16 (of 19)</title><link>http://www.cert.org/blogs/insider_threat/2013/02/common_sense_guide_to_mitigating_insider_threats_-_best_practice_16_of_19.html</link><description>This sixteenth of 19 blog posts about the fourth edition of the Common   Sense Guide to Mitigating Insider Threats describes Practice 16: Develop a formalized insider threat program.</description><pubDate>Wed, 06 Feb 2013 06:38:07 -0500</pubDate></item>'
    
    
    soup = BeautifulStoneSoup(xml)
    item = soup('item')[0]
    print item('pubdate'), item('link')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2020-07-24
      • 2012-04-02
      • 2013-11-03
      相关资源
      最近更新 更多