gpt4 book ai didi

xml-parsing - 使用 Python3 从 XML 中提取元素?

转载 作者:行者123 更新时间:2023-12-02 05:18:45 25 4
gpt4 key购买 nike

我正在尝试编写一个 Python 3 脚本,我在其中查询 Web API 并接收 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 查询有效,通过调试器我可以看到“root”变量中的所有信息。我的问题是我无法弄清楚如何从返回的 XML 中提取类似 ASN ( <asn></asn> ) 的内容。一天以来,我一直在用各种各样的发现、查找和所有其他类型的方法来解决这个问题,但还是没能破解这个问题。我想我已经到了面面俱到的地步,我在互联网上找到的每个例子似乎都无济于事。谁能给我一个代码片段,它可以从树结构中提取 XML 元素的内容?

非常感谢

蒂姆

最佳答案

我建议使用 Beautiful Soup .

从 xml 代码中提取数据时,它非常强大。

例子:

from bs4 import BeautifulSoup
soup = BeautifulSoup(targetURL)

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

关于xml-parsing - 使用 Python3 从 XML 中提取元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com