我正在使用 pinnacle(投注)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()')
但是这不起作用。
最佳答案
如果您想解析内存中的对象(在您的情况下为字符串),请使用 etree.fromstring(<obj>)
-- etree.parse
需要类似文件的对象或文件名 -- Docs
例如:
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>
关于python - Python 中的 XML 和 lxml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088231/