gpt4 book ai didi

Python 和 ElementTree : write() isn't working properly

转载 作者:行者123 更新时间:2023-11-30 23:38:47 25 4
gpt4 key购买 nike

第一个问题。如果我搞砸了,请告诉我。

好的,我需要做的是以下事情。我正在尝试使用 Python 从 API 获取一些数据。 API 将其以 XML 形式发送给我。我正在尝试使用 ElementTree 来解析它。

现在,每次我从 API 请求信息时,情况都会有所不同。我想构建一个我获得的所有数据的列表。我可以使用 Python 的列表,但由于我想在最后将其保存到一个文件中,所以我想 - 为什么不使用 ElementTree 来实现这一点。

从一个元素开始,我们称之为 ListE。调用API,解析XML,从ElementTree中获取根元素。将根元素作为子元素添加到 ListE 中。再次调用API,一切从头再来。最后ListE应该是一个Element,其子元素是每个API调用的结果。最后,只需将 ListE 包装到 ElementTree 中即可使用 ElementTree write() 函数。下面是代码。

import xml.etree.ElementTree as ET

url = "http://http://api.intrade.com/jsp/XML/MarketData/ContractBookXML.jsp?id=769355"

try:
returnurl=urlopen(url)
except IOError:
exit()

tree = ET.parse(returnurl)
root = tree.getroot()

print "root tag and attrib: ",root.tag, root.attrib

historyE = ET.Element('historical data')
historyE.append(root)
historyE.append(root)

historyET = ET.ElementTree(historyE)
historyET.write('output.xml',"UTF-8")

程序不返回任何错误。问题是当我要求浏览器打开它时,它声称存在语法错误。用记事本打开文件,我发现:

<?xml version='1.0' encoding='UTF-8'?>
<historical data><ContractBookInfo lastUpdateTime="0">
<contractInfo conID="769355" expiryPrice="100.0" expiryTime="1357334563000" state="S" vol="712" />
</ContractBookInfo><ContractBookInfo lastUpdateTime="0">
<contractInfo conID="769355" expiryPrice="100.0" expiryTime="1357334563000" state="S" vol="712" />
</ContractBookInfo></historical data>

我认为语法错误的原因是“历史数据”和“ContractBookInfo lastUpdateTime =”0“”之间没有空格或回车。有建议吗?

最佳答案

问题出在这里:

historyE = ET.Element('historical data')

您不应该使用空格。正如 Wikipedia 上所总结的:

The element tags are case-sensitive; the beginning and end tags must match exactly. Tag names cannot contain any of the characters !"#$%&'()*+,/;<=>?@[]^`{|}~, nor a space character, and cannot start with -, ., or a numeric digit.

参见this section XML 规范的详细信息(“名称中允许使用几乎所有字符,除了那些可以用作分隔符或合理地可以用作分隔符的字符。”)

关于Python 和 ElementTree : write() isn't working properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14167496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com