【发布时间】:2022-01-01 10:13:48
【问题描述】:
我有一个包含以下数据的 xml 链接 (http://api.worldbank.org/v2/countries):
<wb:countries xmlns:wb="http://www.worldbank.org" page="1" pages="6" per_page="50" total="299">
<wb:country id="ABW">
<wb:iso2Code>AW</wb:iso2Code>
<wb:name>Aruba</wb:name>
<wb:region id="LCN" iso2code="ZJ">Latin America & Caribbean </wb:region>
<wb:adminregion id="" iso2code=""/>
<wb:incomeLevel id="HIC" iso2code="XD">High income</wb:incomeLevel>
<wb:lendingType id="LNX" iso2code="XX">Not classified</wb:lendingType>
<wb:capitalCity>Oranjestad</wb:capitalCity>
<wb:longitude>-70.0167</wb:longitude>
<wb:latitude>12.5167</wb:latitude>
</wb:country>
<wb:country id="AFE">
<wb:iso2Code>ZH</wb:iso2Code>
<wb:name>Africa Eastern and Southern</wb:name>
<wb:region id="NA" iso2code="NA">Aggregates</wb:region>
<wb:adminregion id="" iso2code=""/>
<wb:incomeLevel id="NA" iso2code="NA">Aggregates</wb:incomeLevel>
<wb:lendingType id="" iso2code="">Aggregates</wb:lendingType>
<wb:capitalCity/>
<wb:longitude/>
<wb:latitude/>
</wb:country>
</wb:countries>
我试图解析收入水平,但它返回(无) 如何使用 BeautifulSoup 到达 xml 文本中的文本(例如:高收入)? 我试过这段代码,但它不能正常工作!
import requests
#import re
from bs4 import BeautifulSoup
url = 'http://api.worldbank.org/v2/countries'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'lxml')
countries= soup.findAll('wb:country')
for country in countries:
name = country.find("wb:name").text
code = country.find('wb:iso2code').text
incomeLevel = country.find('wb:incomeLevel', {"iso2code":"XD"})
print(f"{name}, {code}, {incomeLevel}")
【问题讨论】:
标签: python xml web-scraping beautifulsoup