- Сам формат RSS порівняно легко читається як автоматизованими процесами, так і людьми.
- RSS, оброблений у цьому підручнику, є RSS-каналом найпопулярніших новин із популярного сайту новин. Ви можете перевірити це тут . Наша мета — обробити цей канал RSS (або файл XML) і зберегти його в іншому форматі для подальшого використання.
#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: - Завантажте RSS-канал із зазначеної URL-адреси та збережіть його як файл XML.
- Проаналізуйте XML-файл, щоб зберегти новини як список словників, де кожен словник є окремою новиною.
- Збережіть новини у файл CSV.
- Ви можете переглянути інші RSS-канали веб-сайту новин, використаного у прикладі вище. Ви можете спробувати створити розширену версію наведеного вище прикладу, проаналізувавши також інші канали RSS.
- Ви фанат крикету? Потім це rss-стрічка повинна бути вам цікава! Ви можете проаналізувати цей XML-файл, щоб отримати інформацію про живі матчі з крикету та використати його для створення програми сповіщень на робочому столі!
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 у нашому локальному каталозі. Щоб дізнатися більше про те, як працює модуль запитів, перегляньте цю статтю: Запити GET і POST за допомогою Python
Ось ми використовуємо xml.etree.ElementTree (коротше називати це ET) модуль. Дерево елементів має два класи для цієї мети - ElementTree представляє весь XML-документ у вигляді дерева елемент представляє один вузол у цьому дереві. Взаємодія з усім документом (читання та запис до/з файлів) зазвичай виконується на ElementTree рівень. Взаємодія з одним елементом XML і його піделементами здійснюється на елемент рівень. Гаразд, давайте переглянемо parseXML() function now: tree = ET.parse(xmlfile)Here we create an ElementTree об'єкт шляхом розбору переданого xmlфайл.
root = tree.getroot()getrooted() функція повертає корінь дерево як елемент 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 пункт елемент. ./channel/item насправді XPath синтаксис (XPath — це мова для адресації частин документа XML). Тут ми хочемо знайти все пункт онуки канал діти в корінь (позначається «.») елемент. Ви можете прочитати більше про підтримуваний синтаксис XPath тут . 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 пункт елементів, де кожен пункт елемент містить одну новину. Отже, ми створюємо порожній новини 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'] child.attrib це словник усіх атрибутів, пов’язаних з елементом. Тут нас цікавить url атрибутом медіа:контент namespace tag. Now for all other children we simply do: news[child.tag] = child.text.encode('utf8') child.tag містить назву дочірнього елемента. дитина.текст 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 новини . Нарешті цей список повернуто.
Як бачите, дані ієрархічного файлу XML було перетворено на простий файл CSV, щоб усі новини зберігалися у формі таблиці. Це також полегшує розширення бази даних. Також можна використовувати JSON-подібні дані безпосередньо у своїх програмах! Це найкраща альтернатива для отримання даних із веб-сайтів, які не надають загальнодоступний API, але надають деякі канали RSS. Можна знайти весь код і файли, використані в статті вище тут . Що далі?