Reputation: 53
I have a basic script that can parse the temperature, dew point, altimeter, etc. However, how can I parse a conditional string like the sky condition? I'd like to parse the data and have it print: "Sky Condition: few at 2000 ft AGL" for example.
import xml.etree.ElementTree as ET
from urllib import urlopen
link = urlopen('http://weather.aero/dataserver_current/httpparam?dataSource=metars& requestType=retrieve&format=xml&stationString=KSFO&hoursBeforeNow=1')
tree = ET.parse(link)
root = tree.getroot()
data = root.findall('data/METAR')
for metar in data:
print metar.find('temp_c').text
Upvotes: 0
Views: 278
Reputation: 6005
The page you are retrieving has a structure something like this:
<METAR>
<!-- snip -->
<sky_condition sky_cover="FEW" cloud_base_ft_agl="2000"/>
<sky_condition sky_cover="BKN" cloud_base_ft_agl="18000"/>
</METAR>
So what you are asking is how to extract XML attributes. The xml.etree.ElementTree docs states that these are stored in a dictionary called attrib
. So your code would look something like this:
data = root.findall('data/METAR')
for sky in data.findall('sky_condition'):
print "Sky Condition: {0} at {1} ft AGL".format(
sky.attrib['sky_cover'],
sky.attrib['cloud_base_ft_agl']
)
Upvotes: 2