解析网站上的数据(.xml)

时间:2013-05-22 14:29:47

标签: python xml parsing xml-parsing

我试图解析网站上的数据,我可以执行以下操作:

import xml.etree.ElementTree as ET
from urllib import urlopen

link = urlopen('http://www.yr.no/place/Norway/Sør-Trøndelag/Trondheim/Trondheim/varsel.xml')
tree = ET.parse(link)
root = tree.getroot()

data = root.findall('meta')
for metar in data:
    print metar.find('lastupdate').text

这是一个有效的例子。但是我需要解析临时值和windspeed名称ect。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

这是xpath的作业:

# -*- coding: utf-8 -*-

import xml.etree.ElementTree as ET
from urllib import urlopen

link = urlopen('http://www.yr.no/place/Norway/Sør-Trøndelag/Trondheim/Trondheim/varsel.xml')
tree = ET.parse(link)
root = tree.getroot()

data = root.findall('.//windSpeed')
results = [item.attrib for item in data]
print results

打印:

[{'mps': '2.4', 'name': 'Light breeze'},
 {'mps': '2.4', 'name': 'Light breeze'},
 {'mps': '1.9', 'name': 'Light breeze'},
 {'mps': '0.5', 'name': 'Light air'},
 {'mps': '3.6', 'name': 'Gentle breeze'},
...