- Sam RSS format je relativno jednostavan za čitanje kako automatiziranim procesima tako i ljudima.
- RSS obrađen u ovom vodiču je RSS izvor najvažnijih vijesti s popularne web stranice s vijestima. Možete provjeriti ovdje . Naš cilj je obraditi ovaj RSS feed (ili XML datoteku) i spremiti ga u nekom drugom formatu za buduću upotrebu.
#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: - Učitajte RSS feed s navedenog URL-a i spremite ga kao XML datoteku.
- Raščlanite XML datoteku da biste spremili vijesti kao popis rječnika gdje je svaki rječnik jedna vijest.
- Spremite vijesti u CSV datoteku.
- Možete pogledati više rss feedova web stranice s vijestima korištene u gornjem primjeru. Možete pokušati izraditi proširenu verziju gornjeg primjera tako da analizirate i druge rss feedove.
- Jeste li ljubitelj kriketa? Zatim ovaj rss feed mora vas zanimati! Možete raščlaniti ovu XML datoteku kako biste izgrebali informacije o utakmicama kriketa uživo i upotrijebili ih za izradu obavijesti za radnu površinu!
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 u našem lokalnom imeniku. Za više informacija o tome kako radi modul zahtjeva slijedite ovaj članak: GET i POST zahtjevi pomoću Pythona
Ovdje koristimo xml.etree.ElementTree (nazovite ga ukratko ET) modul. Element Tree ima dvije klase za ovu svrhu - ElementTree predstavlja cijeli XML dokument kao stablo i Element predstavlja jedan čvor u ovom stablu. Interakcije s cijelim dokumentom (čitanje i pisanje u/iz datoteka) obično se obavljaju na ElementTree razini. Interakcije s jednim XML elementom i njegovim podelementima vrše se na Element razini. U redu, prođimo kroz parseXML() function now: tree = ET.parse(xmlfile)Here we create an ElementTree objekt raščlanjivanjem prijeđenog xmlfoteka.
root = tree.getroot()dobiti korijen () funkcija vraća korijen drvo kao 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 artikal element. ./kanal/stavka zapravo je XPath sintaksu (XPath je jezik za adresiranje dijelova XML dokumenta). Ovdje želimo pronaći sve artikal unuci od kanal djeca od korijen (označeno s '.') element. Možete pročitati više o podržanoj XPath sintaksi ovdje . 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 artikal elementi gdje svaki artikal element sadrži jednu vijest. Tako stvaramo prazno vijesti 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'] dijete.attrib je rječnik svih atributa povezanih s elementom. Ovdje nas zanima url atribut od mediji: sadržaj namespace tag. Now for all other children we simply do: news[child.tag] = child.text.encode('utf8') dijete.oznaka sadrži naziv podređenog elementa. dijete.tekst 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 vijesti . Na kraju se ovaj popis vraća.
Kao što vidite, podaci hijerarhijske XML datoteke pretvoreni su u jednostavnu CSV datoteku tako da su sve vijesti pohranjene u obliku tablice. To također olakšava proširenje baze podataka. Također se mogu koristiti podaci nalik JSON-u izravno u njihovim aplikacijama! Ovo je najbolja alternativa za izvlačenje podataka s web stranica koje ne pružaju javni API, ali pružaju neke RSS izvore. Sav kod i datoteke korištene u gornjem članku mogu se pronaći ovdje . Što dalje?