1

我正在尝试为元素“”的第一个实例解析 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。

任何建议将不胜感激。

4

1 回答 1

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')
于 2013-02-07T20:45:29.237 回答