Python——RSS 提要



RSS(富網站摘要)是用於傳遞定期更改的網路內容的一種格式。很多新聞相關網站、網路日誌和其他線上釋出者會以 RSS 提要的形式將他們的內容分發給需要的人。在 python 中,我們藉助以下程式包來閱讀和處理這些提要。

pip install feedparser

提要結構

在下面的示例中,我們獲取提要的結構,以便我們可以進一步分析我們想處理的提要的哪些部分。

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']

提要標題和帖子

在下面的示例中,我們讀取 rss 提要的標題和頭部。

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

提要詳情

根據上述條目結構,我們可以使用 python 程式從提要獲取必要詳情,如下所示。由於條目是一個字典,我們利用其鍵來生成所需的值。

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
廣告