Python ElementTree找不到工作

时间:2016-05-25 10:34:36

标签: python xml elementtree findall

所以我试图解析一些opendata来构建数据库。 这就是我所做的:

# -*- coding: utf-8 -*-
import urllib
import xml.etree.ElementTree as ET

url = 'http://opendata.cwb.gov.tw/govdownload?dataid=C-A0008-001&authorizationkey=rdec-key-123-45678-011121314'

root = ET.parse(urllib.urlopen(url)).getroot()

locations = root.findall('dataset/location')
print type(locations)
print "Counts:", len(locations)

它返回了:

Counts: 0

我尝试解析其他一些xml数据(更改网址)并且工作正常

我正在处理的xml数据大致如下:

<?xml version="1.0" encoding="UTF-8"?><cwbopendata xmlns="urn:cwb:gov:tw:cwbcommon:0.1">
<identifier>0f819d32-297a-4512-9654-990a565bd080</identifier>
<sender>weather@cwb.gov.tw</sender>
<sent>2016-05-23T16:07:06+08:00</sent>
<status>Actual</status>
<msgType>Issue</msgType>
<dataid>CWB_A0008</dataid>
<scope>Public</scope>
<dataset>
    <location>
        <stationId>72C44</stationId>
        <time>
        <dataTime>105 4_2</dataTime>
        </time>
        <weatherElement>
        <elementName>平均氣溫</elementName>
        <elementValue>
        <value>21.1</value>
        </elementValue>
        .
        .
        .
    </location>
    <location>
    .
    .   
    .

抱歉,我是python和ElementTree的新手,希望得到一些好的建议,谢谢

1 个答案:

答案 0 :(得分:2)

您的XML具有默认名称空间,其URI是'urn:cwb:gov:tw:cwbcommon:0.1'。因此,在声明默认命名空间的元素中,所有没有前缀的元素都将被考虑在该命名空间中:

>>> ns = {'d': 'urn:cwb:gov:tw:cwbcommon:0.1'}
>>> locations = root.findall('d:dataset/d:location', ns)
>>> print "Counts:", len(locations)
Counts: 17

相关:Parsing XML with namespace in Python via 'ElementTree'