[英]XML in Python and lxml
我正在使用piniacle(betting)API,该API返回XML文件。 目前,我将其保存到.xml文件中,如下所示:
req = urllib2.Request(url, headers=headers)
responseData = urllib2.urlopen(req).read()
ofn = 'pinnacle_feed_basketball.xml'
with open(ofn, 'w') as ofile:
ofile.write(responseData)
parse_xml()
然后在parse_xml函数中将其打开
tree = etree.parse("pinnacle_feed_basketball.xml")
fdtime = tree.xpath('//rsp/fd/fdTime/text()')
我假设将其另存为XML文件,然后不必读取该文件,但是如果不这样做,我将无法使其正常工作。
我尝试将responseData
传递给parsexml()
函数
parse_xml(responseData)
然后在功能
tree = etree.parse(responseData)
fdtime = tree.xpath('//rsp/fd/fdTime/text()')
但这是行不通的。
但是在两种情况下都传递一个字符串pinnacle_feed_basketball.xml
字符串和responseData
,这也是一个字符串。
在第一种情况下,应为:
with open("pinnacle_feed_basketball.xml") as f:
tree = etree.parse(f)
在第二种情况下:
root = etree.fromstring(responseData) # note that you are not getting an "ElementTree" object here
仅供参考, urllib2.urlopen(req)
也是一个类似于文件的对象 :
tree = etree.parse(urllib2.urlopen(req))
如果要解析内存中的对象(在您的情况下为字符串),请使用etree.fromstring(<obj>)
- etree.parse
需要一个类似文件的对象或文件名- 文档
例如:
import urllib2, lxml.etree as etree
url = 'http://www.xmlfiles.com/examples/note.xml'
headers = {}
req = urllib2.Request(url, headers=headers)
responseData = urllib2.urlopen(req).read()
element = etree.fromstring(responseData)
print(element)
print(etree.tostring(element, pretty_print=True))
输出:
<Element note at 0x2c29dc8>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.