Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Created November 27, 2012 10:39
Show Gist options
  • Save davidwtbuxton/4153560 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/4153560 to your computer and use it in GitHub Desktop.
Parsing XML
# Python 3
# http://www.reddit.com/r/learnpython/comments/13ugqf/getting_information_from_xml_python_3/
from xml.etree import ElementTree as ET
from urllib import request
URL = 'http://weather.yahooapis.com/forecastrss?w=3369&u=c'
# XML name-space for yweather elements. Note you have to use the correct
# name-space when selecting elements, which is what all the '{%s}' stuff
# is about. Also note ElementTree's XPath implementation is currently stupid,
# but works fine if you know how stupid it is.
NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'
def main(url):
# Fetch XML response.
response = request.urlopen(url)
# Parse the response with ElementTree
tree = ET.parse(response)
# Wind chill and atmosphere are nested in the <channel> tag
wind_element = tree.find('./channel/{%s}wind' % NS)
atmos_element = tree.find('./channel/{%s}atmosphere' % NS)
print('wind:', wind_element.attrib)
print('atmosphere:', atmos_element.attrib)
# Forecast with temperature belongs to repeating <item> elements
for cond_element in tree.findall('./channel/item/{%s}condition' % NS):
print('condition:', cond_element.attrib)
for forecast_element in tree.findall('./channel/item/{%s}forecast' % NS):
print('forecast:', forecast_element.attrib)
if __name__ == "__main__":
main(URL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment