1

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

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

这是一个有效的例子。但我需要解析 temp 值和windspeedname ect。我怎样才能做到这一点?

4

1 回答 1

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'},
...
于 2013-05-22T14:42:13.147 回答