在python3中读取/解析XML url的最佳方法



我读了很多类似的问题的不同答案,但似乎没有人提供一个简单的解决方案。

假设有一个像这样的远程 url https://www.emidius.eu/fdsnws/event/1/query?eventid=quakeml:eu.ahead/event/13270512_0000_000&format=xml 最终目标是获取一个可用的 python 对象(例如字典或类似 json 的对象(。

如果将xml另存为本地文件,我确实找到了不同的方法:

import xml.etree.ElementTree as ET
file = '/home/user/query.xml'
tree = ET.parse(file)
root = tree.getroot()
for c in root:
print(c.tag)
for i in c:
print(i.tag)

我没有找到一种方法(使用本机 python 模块(来增加 url 字符串并获取对象。

好的,我认为最好的解决方案是这个:

import xml.etree.ElementTree as ET
import urllib.request
opener = urllib.request.build_opener()
url = 'https://www.emidius.eu/fdsnws/event/1/query?eventid=quakeml:eu.ahead/event/13270512_0000_000&includeallorigins=true&includeallmagnitudes=true&format=xml'
tree = ET.parse(opener.open(url))

这有效,但你不需要build_opener()。 您可以为某些特定情况或协议构建自定义打开器,但使用普通的 https。所以你可以只使用

import urllib.request
import xml.etree.ElementTree as ET
url = 'https://www.emidius.eu/fdsnws/event/1/query?eventid=quakeml:eu.ahead/event/13270512_0000_000&includeallorigins=true&includeallmagnitudes=true&format=xml'
with urllib.request.urlopen(url) as response:
html = ET.fromstring(response.read().decode())

最新更新