Discuss / Python / 小白交作业

小白交作业

Topic source

#作业 from urllib import request

class weatherSaxHandler(object): weather={'forecast':[],'city':''} def start_element(self,name,attrs): if name=="yweather:location": self.weather['city']=attrs['city'] elif name=='yweather:forecast': self.weather['forecast'].append({ 'date': attrs['date'], 'high': attrs['high'], 'low': attrs['low'] })

def parseXml(xml_str): handler=weatherSaxHandler() parser=ParserCreate() parser.StartElementHandler=handler.start_element parser.Parse(xml_str) return handler.weather

with request.urlopen('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml') as f: result=parseXml(f.read().decode('utf-8')) print(result['city'].lower()=="beijing")


  • 1

Reply