打印xml节点python x

2024-06-26 13:40:35 发布

您现在位置:Python中文网/ 问答频道 /正文

对于此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)

Tags: keynamedevimportresthttpnetas
1条回答
网友
1楼 · 发布于 2024-06-26 13:40:35
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)

我不认为你需要先写一个文件然后再分析它?我的解决方案显示了一个可能的解决方案,我相信有很多。你知道吗

简要说明:解码部分使二进制“string”成为ET可以使用的字符串。在findall部分,我必须包含“.”以便从根元素开始搜索,“/”包括所有深度的所有相对节点。此外,还必须包含默认名称空间。希望这有帮助。你知道吗

相关问题 更多 >