- يعد تنسيق 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 باختصار) الوحدة النمطية. تحتوي Element Tree على فئتين لهذا الغرض - ElementTree يمثل مستند XML بأكمله كشجرة و عنصر يمثل عقدة واحدة في هذه الشجرة. عادةً ما تتم التفاعلات مع المستند بأكمله (القراءة والكتابة من/إلى الملفات) على ملف ElementTree مستوى. تتم التفاعلات مع عنصر XML واحد وعناصره الفرعية على عنصر مستوى. حسنًا، دعنا نذهب عبر تحليلXML() function now: tree = ET.parse(xmlfile)Here we create an ElementTree الكائن عن طريق تحليل ما تم تمريره com.xmlfile.
root = tree.getroot()تجذر() وظيفة إرجاع جذر شجرة ك عنصر 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 غرض عنصر. ./القناة/البند هو في الواقع 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 يحتوي على اسم العنصر الفرعي. Child.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 عناصر جديدة . وأخيراً تم إرجاع هذه القائمة.
كما ترون، تم تحويل بيانات ملف XML الهرمي إلى ملف CSV بسيط بحيث يتم تخزين جميع القصص الإخبارية في شكل جدول. وهذا يجعل من السهل توسيع قاعدة البيانات أيضًا. كما يمكن للمرء استخدام البيانات المشابهة لـ JSON مباشرةً في تطبيقاته! هذا هو البديل الأفضل لاستخراج البيانات من مواقع الويب التي لا توفر واجهة برمجة تطبيقات عامة ولكنها توفر بعض خلاصات RSS. يمكن العثور على جميع الأكواد والملفات المستخدمة في المقالة أعلاه هنا . ماذا بعد؟