2012-09-21 66 views
2

我正在嘗試編寫一個Python 3腳本,用於查詢Web API並接收XML響應。響應看起來是這樣的 -用Python3從XML中提取元素?

<?xml version="1.0" encoding="UTF-8"?> 
<ipinfo> 
    <ip_address>4.2.2.2</ip_address> 
    <ip_type>Mapped</ip_type> 
    <anonymizer_status/> 
    <Network> 
     <organization>level 3 communications inc.</organization> 
     <OrganizationData> 
    <home>false</home> 
     <organization_type>Telecommunications</organization_type> 
     <naics_code>518219</naics_code> 
    <isic_code>J6311</isic_code> 
     </OrganizationData>  
     <carrier>level 3 communications</carrier> 
     <asn>3356</asn> 
     <connection_type>tx</connection_type> 
     <line_speed>high</line_speed> 
     <ip_routing_type>fixed</ip_routing_type> 
     <Domain> 
     <tld>net</tld> 
     <sld>bbnplanet</sld> 
     </Domain> 
    </Network> 
    <Location> 
     <continent>north america</continent> 
     <CountryData> 
     <country>united states</country> 
     <country_code>us</country_code> 
     <country_cf>99</country_cf> 
     </CountryData> 
     <region>southwest</region> 
     <StateData> 
     <state>california</state> 
     <state_code>ca</state_code> 
     <state_cf>88</state_cf> 
     </StateData> 
     <dma>803</dma> 
     <msa>31100</msa> 
     <CityData> 
     <city>san juan capistrano</city> 
     <postal_code>92675</postal_code> 
     <time_zone>-8</time_zone> 
     <area_code>949</area_code> 
     <city_cf>77</city_cf> 
     </CityData> 
     <latitude>33.499</latitude> 
     <longitude>-117.662</longitude> 
    </Location> 
</ipinfo> 

這是我的代碼至今 -

import urllib.request 
import urllib.error 
import sys 
import xml.etree.ElementTree as etree 

… 

try: 
    xml = urllib.request.urlopen(targetURL, data=None) 
except urllib.error.HTTPError as e: 
    print("HTTP error: " + str(e) + " URL: " + targetURL) 
    sys.exit() 

tree = etree.parse(xml) 
root = tree.getroot() 

的API查詢工作,並通過調試,我可以看到所有信息的「根」變量中。我的問題是,我一直無法弄清楚如何從返回的XML中提取像ASN(<asn></asn>)這樣的東西。一直以來,我一直在用各種各樣的發現,findalls和所有其他種類的方法來對抗這一點,但沒有能夠解決這個問題。我認爲我已經達到了無法看到所有樹木的地步,而且我在互聯網上找到的每個例子似乎都沒有幫助。有人能告訴我一個代碼片段,它可以從樹結構中提取XML元素的內容嗎?

非常感謝

回答

0

我會建議使用Beautiful Soup

從xml-code中提取數據非常強大。

實施例:

from bs4 import BeautifulSoup 
soup = BeautifulSoup(targetURL) 

soup.find_all('asn') #Would return all the <asn></asn> tags found!