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