Python: Parsing Online XML The Easy Way

On my Raspberry Pi VFD project, I needed a way to download the XML feed from to display the weather. After hours of searching Google and trying different things, I finally came across a way that actually works, using lxml and urllib2. I am still very new at Python, so I don’t completely understand it yet. Here is the code I used that works for me, hopefully will work for you too:

#!/usr/bin/env python
from lxml import etree
import urllib2
url = ''
fp = urllib2.urlopen(url)
doc = etree.parse(fp)
temp = doc.xpath("//current_observation/temp_f")[0].text
temp = temp[:-2]
print temp

Of course, this just returns the temperature in Fahrenheit. If you look at the xml itself you can see that the section I was interested in was “temp_f” under “current_observation”. Another interesting Python trick is “temp[:-2]“. This removes the right 2 characters from the string, changing 37.6 to 37. I also later made a variable for weather which returns things like “overcast”. That line looks like weather = doc.xpath("//current_observation/weather")[0].text. Hopefully this much simpler example than what I could find on Google will make things a little clearer for everyone.

To use this, make sure you install lxml:

sudo apt-get install python3-lxml

Note: I lost the URL to the code I ended up using, so I can’t give proper credit, sorry!