#!/usr/bin/python3.5 # from xml.parsers.expat import ParserCreate class defaultsax(object): def __init__(self): self.db = {} def start_element(self, name, attrs): print('sax:start_elementname:%s,attrs:%s' % (name,str(attrs))) def end_element(self, name): print('sax:end_element:%s' % name) pass def char_data(self, text): print('sax:char_data: %s' % text) #pass xml = r'''<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"> <channel> <title>Yahoo! Weather - Beijing, CN</title> <lastBuildDate>Wed, 27 May 2015 11:00 am CST</lastBuildDate> <yweather:location city="Beijing" region="" country="China"/> <yweather:units temperature="C" distance="km" pressure="mb" speed="km/h"/> <yweather:wind chill="28" direction="180" speed="14.48" /> <yweather:atmosphere humidity="53" visibility="2.61" pressure="1006.1" rising="0" /> <yweather:astronomy sunrise="4:51 am" sunset="7:32 pm"/> <item> <geo:lat>39.91</geo:lat> <geo:long>116.39</geo:long> <pubDate>Wed, 27 May 2015 11:00 am CST</pubDate> <yweather:condition text="Haze" code="21" temp="28" date="Wed, 27 May 2015 11:00 am CST" /> <yweather:forecast day="Wed" date="27 May 2015" low="20" high="33" text="Partly Cloudy" code="30" /> <yweather:forecast day="Thu" date="28 May 2015" low="21" high="34" text="Sunny" code="32" /> <yweather:forecast day="Fri" date="29 May 2015" low="18" high="25" text="AM Showers" code="39" /> <yweather:forecast day="Sat" date="30 May 2015" low="18" high="32" text="Sunny" code="32" /> <yweather:forecast day="Sun" date="31 May 2015" low="20" high="37" text="Sunny" code="32" /> </item> </channel> </rss> ''' handler = defaultsax() parser = ParserCreate() parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDataHandler = handler.char_data parser.Parse(xml)
執行之後發現end_element字段沒有什麼有用的信息,所有將其刪除之:
def end_element(self, name): #print('sax:end_element:%s' % name) pass
爲了方便分析,char_data字段也先不顯示:
def char_data(self, text): print('sax:char_data: %s' % text) #pass
改好後,執行腳本,獲得以下內容(只截取一部分):
很明顯,name的內容也沒有我們需要的內容,不過要根據name對不同行內容做處理,attrs是我們需要的真正內容,attrs顯示的格式明顯是字典,這時就可以利用字典的key得到我們想要的,更改start_element段代碼並增加__init__段:
def __init__(self): self.weater = {} #定義一個空字典 def start_element(self, name, attrs): self.weater['na'] = name if self.weater['na'] == 'yweather:location': #對name=yweather:location行的attrs做處理 print('國家:%s,城市:%s' % (attrs['country'],attrs['city']))
保存並執行腳本:
然後根據需要,對每個行做相應的截取,最後得到自己想要的。