【发布时间】:2011-10-25 00:55:56
【问题描述】:
我有一个巨大的 URL 列表,我的任务是将它们提供给一个 python 脚本,如果有的话,它应该吐出提要 URL。是否有 API 库或代码可以提供帮助?
【问题讨论】:
标签: python api rss feed atom-feed
我有一个巨大的 URL 列表,我的任务是将它们提供给一个 python 脚本,如果有的话,它应该吐出提要 URL。是否有 API 库或代码可以提供帮助?
【问题讨论】:
标签: python api rss feed atom-feed
>>> import feedfinder
>>>
>>> feedfinder.feed('scripting.com')
'http://scripting.com/rss.xml'
>>>
>>> feedfinder.feeds('scripting.com')
['http://delong.typepad.com/sdj/atom.xml',
'http://delong.typepad.com/sdj/index.rdf',
'http://delong.typepad.com/sdj/rss.xml']
>>>
【讨论】:
feedfinder2。
我在推荐 Beautiful Soup 解析 HTML 然后获取引用提要的 标记的第二个华夫饼悖论。我常用的代码:
from BeautifulSoup import BeautifulSoup as parser
def detect_feeds_in_HTML(input_stream):
""" examines an open text stream with HTML for referenced feeds.
This is achieved by detecting all ``link`` tags that reference a feed in HTML.
:param input_stream: an arbitrary opened input stream that has a :func:`read` method.
:type input_stream: an input stream (e.g. open file or URL)
:return: a list of tuples ``(url, feed_type)``
:rtype: ``list(tuple(str, str))``
"""
# check if really an input stream
if not hasattr(input_stream, "read"):
raise TypeError("An opened input *stream* should be given, was %s instead!" % type(input_stream))
result = []
# get the textual data (the HTML) from the input stream
html = parser(input_stream.read())
# find all links that have an "alternate" attribute
feed_urls = html.findAll("link", rel="alternate")
# extract URL and type
for feed_link in feed_urls:
url = feed_link.get("href", None)
# if a valid URL is there
if url:
result.append(url)
return result
【讨论】:
我不知道任何现有的库,但 Atom 或 RSS 提要通常在 <head> 部分中用 <link> 标记表示:
<link rel="alternative" type="application/rss+xml" href="http://link.to/feed">
<link rel="alternative" type="application/atom+xml" href="http://link.to/feed">
直截了当的方法是使用像lxml.html 这样的HTML 解析器下载和解析这些URL,并获取相关<link> 标记的href 属性。
【讨论】:
取决于这些提要中信息的格式是否正确(例如,是否所有链接都采用http://.../ 的形式?您知道它们是否都在href 或link 标记中?都是提要中的链接将指向其他提要?等等),我建议从简单的正则表达式到直接解析模块,以从提要中提取链接。
就解析模块而言,我只能推荐beautiful soup。尽管即使是最好的解析器也只能做到这一点——尤其是在我上面提到的情况下,如果你不能保证数据中的所有链接都是指向其他提要的链接;那么你必须自己做一些额外的爬取和探测。
【讨论】: