Python Text Processing 简明教程
Python - Reading RSS feed
RSS(富网站摘要)是一种用来传递定期更改的 Web 内容的格式。许多新闻相关站点、Web 日志和其他在线发布者以 RSS Feed 的形式联合他们的内容提供给想要这些内容的用户。在 Python 中,我们借助以下软件包来读取和处理这些 Feed。
pip install feedparser
Feed Structure
在下面的示例中,我们获取了 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 Title and Posts
在以下示例中,我们读取了 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 Details
基于上述条目结构,我们可以使用 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