Python - 读取 RSS Feed



RSS(网站摘要)是一种用于传输定期更改的网络内容的格式。许多新闻相关的网站、网络日志和其他在线出版商将其内容作为 RSS Feed 传播给任何想要它的人。在 Python 中,我们借助以下包来读取和处理这些 Feed。

pip install feedparser

Feed 结构

在下面的示例中,我们获取 Feed 的结构,以便我们可以进一步分析我们想要处理的 Feed 的哪些部分。

import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
entry = NewsFeed.entries[1]

print entry.keys()

运行上述程序后,我们将得到以下输出:

['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']

Feed 标题和文章

在下面的示例中,我们读取 RSS Feed 的标题和摘要。

import feedparser

NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")

print 'Number of RSS posts :', len(NewsFeed.entries)

entry = NewsFeed.entries[1]
print 'Post Title :',entry.title

运行上述程序后,我们将得到以下输出:

Number of RSS posts : 5
Post Title : Cong-JD(S) in SC over choice of pro tem speaker

Feed 详情

基于上述条目结构,我们可以使用如下所示的 Python 程序从 Feed 中提取必要的详细信息。由于条目是一个字典,我们利用它的键来产生所需的值。

import feedparser

NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")

entry = NewsFeed.entries[1]

print entry.published
print "******"
print entry.summary
print "------News Link--------"
print entry.link

运行上述程序后,我们将得到以下输出:

Fri, 18 May 2018 20:13:13 GMT
******
Controversy erupted on Friday over the appointment of BJP MLA K G Bopaiah as pro tem speaker for the assembly, with Congress and JD(S) claiming the move went against convention that the post should go to the most senior member of the House. The combine approached the SC to challenge the appointment. Hearing is scheduled for 10:30 am today.
------News Link--------
https://timesofindia.indiatimes.com/india/congress-jds-in-sc-over-bjp-mla-made-pro-tem-speaker-hearing-at-1030-am/articleshow/64228740.cms
广告