如何解决解析XML在python中创建格式不正确的错误
我正在尝试使用以下代码从URL https://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文档,并且在浏览器中打开后似乎解析得很好。
解决方法
您很可能会返回json。要进行验证,请尝试在HTTPResponse对象上打印info()
的值,然后查看“ Content-Type”:
response = urllib.request.urlopen(url)
print(response.info())
要请求XML,请创建一个Request对象并设置标题(用于测试的打印树):
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....
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。