对于这个 xml
http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key= {BingMapsKey}
我正在尝试打印每个位置的名称
import requests
import xml.etree.ElementTree as ET
url = 'http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key={BingMapsKey}'
response = requests.get(url)
with open('loc.xml', 'wb') as file:
file.write(response.content)
mytree = ET.parse('/Users/xxxxxxx/Desktop/pscripts/loc.xml')
name = mytree.findall('Name')
for n in name:
n = name.text
print (n)
最佳答案
import requests
import xml.etree.ElementTree as ET
url = 'http://dev.virtualearth.net/REST/v1/Locations?q=St%20Mard,%20FR&o=xml&key={BingMapsKey} '
response = requests.get(url).content.decode("utf-8-sig")
mytree = ET.fromstring(response)
name = mytree.findall('.//{http://schemas.microsoft.com/search/local/ws/rest/v1}Name')
for n in name:
print (n.text)
我认为您不需要在解析文件之前先编写文件?我的解决方案显示了一种可能的解决方案,而且我确信有很多解决方案。
简单说明:解码部分使二进制“字符串”成为ET可以使用的字符串。在 findall 部分中,我必须包含“.”。从根元素开始搜索,“//”包括所有深度的所有相关节点。此外,必须包含默认 namespace 。希望这会有所帮助。
关于python - 打印 xml 节点 python xtree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330288/