第一个问题。如果我搞砸了,请告诉我。
好的,我需要做的是以下。我正在尝试使用 Python 从 API 获取一些数据。API 以 XML 格式将其发送给我。我正在尝试使用 ElementTree 来解析它。
现在,每次我从 API 请求信息时,都会有所不同。我想构建一个我得到的所有数据的列表。我可以使用 Python 的列表,但由于我想在最后将它保存到一个文件中 - 为什么不也使用 ElementTree。
从一个元素开始,我们称之为 ListE。调用 API,解析 XML,从 ElementTree 中获取根元素。将根元素作为子元素添加到 ListE 中。再次调用 API,然后重新开始。最后 ListE 应该是一个元素,其子元素是每个 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”'之间没有空格或返回。建议?