使用键用Python解析XML
我有以下XML文件使用键用Python解析XML,python,xml,xml-parsing,Python,Xml,Xml Parsing,我有以下XML文件 <GeocodeResponse> <status>OK</status> <result> <type>street_address</type> <formatted_address>277 Bedford Ave, Brooklyn, NY 11211, USA</formatted_address> <address_c
<GeocodeResponse>
<status>OK</status>
<result>
<type>street_address</type>
<formatted_address>277 Bedford Ave, Brooklyn, NY 11211, USA</formatted_address>
<address_component>
<long_name>277</long_name>
<short_name>277</short_name>
<type>street_number</type>
</address_component>
<address_component>
<long_name>Bedford Avenue</long_name>
<short_name>Bedford Ave</short_name>
<type>route</type>
</address_component>
<address_component>
<long_name>Williamsburg</long_name>
<short_name>Williamsburg</short_name>
<type>neighborhood</type>
<type>political</type>
</address_component>
<address_component>
<long_name>11211</long_name>
<short_name>11211</short_name>
<type>postal_code</type>
</address_component>
好啊
街道地址
美国纽约州布鲁克林贝德福德大道277号,邮编:11211
277
277
街道号码
贝德福德大道
贝德福德大街
路线
威廉斯堡
威廉斯堡
邻里
政治的
11211
11211
邮政编码
我希望使用邮政编码作为键返回值11211
。我应该如何解析它并将值作为字符串返回
任何帮助都将不胜感激。您可以使用。我想这会满足你的要求:
from bs4 import BeautifulSoup
def get_by_type(data, some_type):
soup = BeautifulSoup(data, 'xml')
components = soup.find('result').find_all('address_component')
for c in components:
if any(t for t in c.find_all('type') if t.text == some_type):
return c.long_name.text
with open('data.xml') as f:
data = f.read()
print(get_by_type(data, 'postal_code'))
只需将作为第二个参数的字符串更改为get\u by\u type
,即可获得其他值