如何使用 python 从网站解析 XML

How to Parse XML from website using python

我正在尝试从 URL 解析 XML,但出现错误 FileNotFoundError

我哪里做错了?

这是我的代码:

import xml.etree.ElementTree as ET
import requests
url = "http://cs.stir.ac.uk/~soh/BD2spring2022/assignmentdata.php"
params = {'data':'spurpyr'}
response = requests.get (url, params)
xml_content = response.content

tree = ET.parse(xml_content)
root = tree.getroot()
print(root.tag)

ET.parse 从文件解析,而不是 ET.parse 尝试使用 ET.fromstring,这可能会有所帮助。我无法测试你的具体情况,因为你写的 URL 给我一个错误。所以,尝试将您的代码更改为此

import xml.etree.ElementTree as ET
import requests
url = "http://cs.stir.ac.uk/~soh/BD2spring2022/assignmentdata.php"
params = {'data':'spurpyr'}
response = requests.get (url, params)
xml_content = response.content

root = ET.fromstring(xml_content)
print(root.tag)