2016-05-25 11 views
1

Also ich versuche, einige opendata zu analysieren, um eine Datenbank zu erstellen. Hier ist, was ich getan habe:Python ElementTree finden funktioniert nicht

# -*- 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) 

es zurückgegeben:

Counts: 0 

Ich habe versucht, einige andere XML-Daten zu analysieren (die URL ändern) und es funktionierte gut

die XML-Daten I bin am arbeiten ist ungefähr wie:

<?xml version="1.0" encoding="UTF-8"?><cwbopendata xmlns="urn:cwb:gov:tw:cwbcommon:0.1"> 
<identifier>0f819d32-297a-4512-9654-990a565bd080</identifier> 
<sender>[email protected]</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> 
    . 
    . 
    . 

Sorry, ich bin neu zu Python und ElementTree und hoffe, zu Bekomme einige gute Ratschläge, danke

Antwort

1

Dein XML hat den Standard-Namespace, dessen URI 'urn: cwb: gov: tw: cwbcommon: 0.1' lautet. So werden alle Elemente ohne Präfix, innerhalb Element, in dem Standard-Namespace deklariert wird, würde in diesem Namensraum in Betracht gezogen werden:

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

Verwandte: Parsing XML with namespace in Python via 'ElementTree'