0

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
1
  • 1
    You probably should include an illustrative XML sample. Commented Oct 23, 2012 at 14:20

1 Answer 1

2

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']
      )
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, beat me to it :) If you want to reduce lines even more, you could try print 'Sky Condition: {sky_cover} at cloud_base_ft_agl}'.format(**sky.attrib), but yours better fits the 'explicit is better than implicit' model.
@RocketDonkey It felt like there should have been a way to do that. I just forgot about the "unmapping" operator (**). +1
Ha, well I think your version does a better job of explaining, so +1 back atcha :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.