1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#!/usr/bin/python # -*- coding: utf-8 -*- from urllib import urlopen from xml.dom.minidom import parse WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s&u=%s' WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' ERROR_MSG = 'No weather feed' weather_params = ('FRXX0076','c') class YWeatherAPI: def __init__(self): self.options = ['location', 'astronomy', 'units', 'wind', 'atmosphere', 'condition', 'forecast'] def query_api(self, params): try: return self.get_data(parse(urlopen(WEATHER_URL % params))) except: return ERROR_MSG def get_data(self, xml): data = {} for option in self.options: param_list = [] for node in xml.getElementsByTagNameNS(WEATHER_NS, option): attrs = node.attributes.keys() options_dict = {} for attr in attrs : value = node.getAttribute(attr) options_dict[attr] = value param_list.append(options_dict) data[option]=param_list return data y = YWeatherAPI() print y.query_api(weather_params)
Refactorings
No refactoring yet !
micheal d.
September 8, 2008, September 08, 2008 17:27, permalink
Well, it depends wether you would like to have some speed increase or a serious speed increase. If first, use xml.sax, if second I advise using cElementTree. Then again for RSS I think sax would be perfect.
Is there a more efficient way to parse the Yahoo weather RSS feed ?