Python - Feed RSS

RSS (Rich Site Summary) è un formato per fornire contenuti web che cambiano regolarmente. Molti siti di notizie, weblog e altri editori online distribuiscono i propri contenuti come feed RSS a chiunque lo desideri. In python ci avvaliamo del pacchetto seguente per leggere ed elaborare questi feed.

pip install feedparser

Struttura del mangime

Nell'esempio seguente otteniamo la struttura del feed in modo da poter analizzare ulteriormente le parti del feed che vogliamo elaborare.

import feedparser
NewsFeed = feedparser.parse("https://timesofindia.indiatimes.com/rssfeedstopstories.cms")
entry = NewsFeed.entries[1]
print entry.keys()

Quando eseguiamo il programma sopra, otteniamo il seguente output:

['summary_detail', 'published_parsed', 'links', 'title', 'summary', 'guidislink', 'title_detail', 'link', 'published', 'id']

Titolo del feed e post

Nell'esempio seguente leggiamo il titolo e l'intestazione del feed 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

Quando eseguiamo il programma sopra, otteniamo il seguente output:

Number of RSS posts : 5
Post Title : Cong-JD(S) in SC over choice of pro tem speaker

Dettagli feed

Sulla base della struttura della voce sopra, possiamo derivare i dettagli necessari dal feed utilizzando il programma Python come mostrato di seguito. Poiché la voce è un dizionario, utilizziamo le sue chiavi per produrre i valori necessari.

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

Quando eseguiamo il programma sopra, otteniamo il seguente output:

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