- El format RSS en si és relativament fàcil de llegir tant per processos automatitzats com per humans.
- L'RSS processat en aquest tutorial és el canal RSS de les notícies principals d'un lloc web de notícies popular. Podeu comprovar-ho aquí . El nostre objectiu és processar aquest canal RSS (o fitxer XML) i desar-lo en un altre format per a un ús futur.
#Python code to illustrate parsing of XML files # importing the required modules import csv import requests import xml.etree.ElementTree as ET def loadRSS(): # url of rss feed url = 'http://www.hindustantimes.com/rss/topnews/rssfeed.xml' # creating HTTP response object from given url resp = requests.get(url) # saving the xml file with open('topnewsfeed.xml' 'wb') as f: f.write(resp.content) def parseXML(xmlfile): # create element tree object tree = ET.parse(xmlfile) # get root element root = tree.getroot() # create empty list for news items newsitems = [] # iterate news items for item in root.findall('./channel/item'): # empty news dictionary news = {} # iterate child elements of item for child in item: # special checking for namespace object content:media if child.tag == '{https://video.search.yahoo.com/mrss': news['media'] = child.attrib['url'] else: news[child.tag] = child.text.encode('utf8') # append news dictionary to news items list newsitems.append(news) # return news items list return newsitems def savetoCSV(newsitems filename): # specifying the fields for csv file fields = ['guid' 'title' 'pubDate' 'description' 'link' 'media'] # writing to csv file with open(filename 'w') as csvfile: # creating a csv dict writer object writer = csv.DictWriter(csvfile fieldnames = fields) # writing headers (field names) writer.writeheader() # writing data rows writer.writerows(newsitems) def main(): # load rss from web to update existing xml file loadRSS() # parse xml file newsitems = parseXML('topnewsfeed.xml') # store news items in a csv file savetoCSV(newsitems 'topnews.csv') if __name__ == '__main__': # calling main function main()
Above code will: - Carregueu el feed RSS des de l'URL especificat i deseu-lo com a fitxer XML.
- Analitzeu el fitxer XML per desar les notícies com una llista de diccionaris on cada diccionari és una sola notícia.
- Deseu les notícies en un fitxer CSV.
- Podeu fer una ullada a més fonts rss del lloc web de notícies utilitzat a l'exemple anterior. Podeu provar de crear una versió ampliada de l'exemple anterior analitzant també altres fonts rss.
- Ets fan del cricket? Aleshores això El feed rss ha de ser del teu interès! Podeu analitzar aquest fitxer XML per obtenir informació sobre els partits de cricket en directe i utilitzar-lo per fer un notificador d'escriptori!
def loadRSS(): # url of rss feed url = 'http://www.hindustantimes.com/rss/topnews/rssfeed.xml' # creating HTTP response object from given url resp = requests.get(url) # saving the xml file with open('topnewsfeed.xml' 'wb') as f: f.write(resp.content) Here we first created a HTTP response object by sending an HTTP request to the URL of the RSS feed. The content of response now contains the XML file data which we save as topnewsfeed.xml al nostre directori local. Per obtenir més informació sobre com funciona el mòdul de sol·licituds, seguiu aquest article: Sol·licituds GET i POST mitjançant Python
Aquí estem utilitzant xml.etree.ElementTree (anomenar-lo ET en breu) mòdul. Element Tree té dues classes per a aquest propòsit: ElementTree representa tot el document XML com un arbre i Element representa un sol node en aquest arbre. Les interaccions amb tot el document (llegir i escriure a/des de fitxers) es fan normalment al ElementTree nivell. Les interaccions amb un únic element XML i els seus subelements es realitzen al Element nivell. D'acord, passem pel parseXML() function now: tree = ET.parse(xmlfile)Here we create an ElementTree objecte analitzant el passat fitxer xml.
root = tree.getroot()arrencar () funció retorna l'arrel de arbre com a Element object.
for item in root.findall('./channel/item'): Now once you have taken a look at the structure of your XML file you will notice that we are interested only in element element. ./canal/element és en realitat XPath sintaxi (XPath és un llenguatge per adreçar parts d'un document XML). Aquí ho volem trobar tot element néts de canal fills de la arrel (indicat per '.') element. Podeu llegir més informació sobre la sintaxi XPath compatible aquí . for item in root.findall('./channel/item'): # empty news dictionary news = {} # iterate child elements of item for child in item: # special checking for namespace object content:media if child.tag == '{https://video.search.yahoo.com/mrss': news['media'] = child.attrib['url'] else: news[child.tag] = child.text.encode('utf8') # append news dictionary to news items list newsitems.append(news) Now we know that we are iterating through element elements on cadascun element L'element conté una notícia. Així que creem un buit notícies dictionary in which we will store all data available about news item. To iterate though each child element of an element we simply iterate through it like this: for child in item:Now notice a sample item element here:
We will have to handle namespace tags separately as they get expanded to their original value when parsed. So we do something like this: if child.tag == '{https://video.search.yahoo.com/mrss': news['media'] = child.attrib['url'] nen.atribut és un diccionari de tots els atributs relacionats amb un element. Aquí ens interessa url atribut de mitjans de comunicació: contingut namespace tag. Now for all other children we simply do: news[child.tag] = child.text.encode('utf8') nen.etiqueta conté el nom de l'element fill. nen.text stores all the text inside that child element. So finally a sample item element is converted to a dictionary and looks like this: {'description': 'Ignis has a tough competition already from Hyun.... 'guid': 'http://www.hindustantimes.com/autos/maruti-ignis-launch.... 'link': 'http://www.hindustantimes.com/autos/maruti-ignis-launch.... 'media': 'http://www.hindustantimes.com/rf/image_size_630x354/HT/... 'pubDate': 'Thu 12 Jan 2017 12:33:04 GMT ' 'title': 'Maruti Ignis launches on Jan 13: Five cars that threa..... } Then we simply append this dict element to the list llocs de notícies . Finalment es torna aquesta llista.
Com podeu veure, les dades del fitxer XML jeràrquic s'han convertit en un simple fitxer CSV de manera que totes les notícies s'emmagatzemen en forma de taula. Això també fa que sigui més fàcil ampliar la base de dades. També es pot utilitzar les dades semblants a JSON directament a les seves aplicacions! Aquesta és la millor alternativa per extreure dades de llocs web que no proporcionen una API pública però que proporcionen alguns canals RSS. Es poden trobar tot el codi i els fitxers utilitzats a l'article anterior aquí . Què després?