RSS(豐富站點(diǎn)摘要)是一種用于提供定期更改的Web內(nèi)容的格式。 許多與新聞相關(guān)的網(wǎng)站,網(wǎng)絡(luò)日志和其他在線發(fā)布商將其內(nèi)容作為RSS Feed聯(lián)合到任何想要它的人。 在python中,借助以下包來讀取和處理這些提要。
pip install feedparser
Feed結(jié)構(gòu)
在下面的示例中,我們獲取了Feed的結(jié)構(gòu),以便可以進(jìn)一步分析要處理的Feed的哪些部分。
import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
entry = NewsFeed.entries[1]
print entry.keys()
執(zhí)行上面示例代碼,得到以下結(jié)果 -
['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']
Feed標(biāo)題和帖子
在下面的示例中,我們讀取了rss feed的標(biāo)題和頭部。
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
執(zhí)行上面示例代碼,得到以下結(jié)果 -
Number of RSS posts : 5
Post Title : Cong-JD(S) in SC over choice of pro tem speaker
Feed詳情
基于上面的輸入結(jié)構(gòu),可以使用python程序從feed中導(dǎo)出必要的細(xì)節(jié),如下所示。 由于項(xiàng)目是字典,所以可利用其鍵來產(chǎn)生所需的值。
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
當(dāng)我們運(yùn)行上面的程序時(shí),得到以下輸出 -
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