Python-text-processing-python-reading-rss-feed

提供:Dev Guides
移動先:案内検索

Python-RSSフィードを読む

RSS(Rich Site Summary)は、定期的に変化するWebコンテンツを配信するための形式です。 多くのニュース関連サイト、ウェブログ、その他のオンライン出版社は、コンテンツを希望する人への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