解析XML会在python中产生格式不正确的错误

2024-04-26 06:49:20 发布

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

我正在尝试使用以下代码从urlhttps://www.predictit.org/api/marketdata/all/解析XML文档:

import xml.etree.ElementTree as ET
import urllib.request

url = 'https://www.predictit.org/api/marketdata/all/'
response = urllib.request.urlopen(url).read().decode('utf-8')
tree = ET.fromstring(response)

但是,我得到了错误ParseError: not well-formed (invalid token): line 1, column 0

要将其转换为python对象,我需要做什么?我确信这是一个XML文档,在浏览器中打开时,它的解析看起来很好


Tags: 代码文档orgimportapiurlresponserequest
1条回答
网友
1楼 · 发布于 2024-04-26 06:49:20

你很可能会得到json。要进行验证,请尝试在HTTPResponse对象上打印info()的值,并查看“内容类型”:

response = urllib.request.urlopen(url)
print(response.info())

要请求XML,请创建一个请求对象并设置标题(打印测试树):

import xml.etree.ElementTree as ET
import urllib.request

url = "https://www.predictit.org/api/marketdata/all/"

request = urllib.request.Request(url, headers={"Content-Type": "application/xml"})
response = urllib.request.urlopen(request)
tree = ET.parse(response)
print(ET.tostring(tree.getroot()).decode())

这将打印(截短以适合SO):

<MarketList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><Markets><MarketData><ID>2721</ID><Name>Which party will win the 2020 U.S....

相关问题 更多 >