支持FeedBurner的Python RSS解析器
我正在写一个用Python制作的解析RSS源的小程序。我用的是feedparser这个库,但在解析FeedBurner的源时遇到了麻烦。现在还有谁需要FeedBurner呢?不过不管怎样……
比如说,我找不到解析以下链接的方法:
http://feeds.wired.com/wired/index
http://feeds2.feedburner.com/ziffdavis/pcmag
当我把这些链接放进feedparser库时,似乎都不行。我试着在网址后面加上?fmt=xml或者?format=xml,但还是没有得到xml格式的内容。
我需要用像BeautifulSoup这样的HTML解析器来解析FeedBurner的源吗?有没有现成的Python公共解析器或者聚合脚本可以处理这个问题呢?
任何建议或帮助都非常感谢。
2 个回答
2
我知道这个问题已经很久了,但我觉得对那些搜索解析Feedburner RSS源的人来说,这里有个简单的代码可以帮助到他们。我用这个代码从Cracked.com的Feedburner获取最新的内容,测试过其他几个网站也都能正常工作。
def GetRSS('RSSurl'):
url_info = urllib.urlopen(RSSurl)
if (url_info):
xmldoc = minidom.parse(url_info)
if (xmldoc):
url = xmldoc.getElementsByTagName('link').firstChild.data
title = xmldoc.getElementsByTagName('title').firstChild.data
print url, print title
只需要把RSSurl替换成你想要的Feedburner页面地址就可以了。而且,正如你可能看到的,如果你想要其他的元素,可以再加一行getElementsByTagName,写上你想要获取的内容。
补充一下:据我所知,这个方法几乎适用于任何RSS源。
5
可能你遇到了版本问题,或者你使用API的方式不对——看到你的错误信息会更有帮助。例如,下面的代码在Python 2.7和feedparser 5.0.1中是可以正常工作的:
>>> import feedparser
>>> url = 'http://feeds2.feedburner.com/ziffdavis/pcmag'
>>> d = feedparser.parse(url)
>>> d.feed.title
u'PCMag.com: New Product Reviews'
>>> d.feed.link
u'http://www.pcmag.com'
>>> d.feed.subtitle
u"First Look At New Products From PCMag.com including Lab Tests, Ratings, Editor's and User's Reviews."
>>> len(d['entries'])
30
>>> d['entries'][0]['title']
u'Canon Color imageClass MF9280cdn'
还有另一个网址的例子:
>>> url = 'http://feeds.wired.com/wired/index'
>>> d = feedparser.parse(url)
>>> d.feed.title
u'Wired Top Stories'
>>> d.feed.link
u'http://www.wired.com/rss/index.xml'
>>> d.feed.subtitle
u'Top Stories<img src="http://www.wired.com/rss_views/index.gif" />'
>>> len(d['entries'])
30
>>> d['entries'][0]['title']
u'Heart of Dorkness: LARPing Goes Haywire in <em>Wild Hunt</em>'