XML in Python and lxml -
i using pinnacle (betting) api returns xml file. @ moment, save .xml file below:
req = urllib2.request(url, headers=headers) responsedata = urllib2.urlopen(req).read() ofn = 'pinnacle_feed_basketball.xml' open(ofn, 'w') ofile: ofile.write(responsedata) parse_xml()
and open in parse_xml function
tree = etree.parse("pinnacle_feed_basketball.xml") fdtime = tree.xpath('//rsp/fd/fdtime/text()')
i presuming saving xml file , reading in file not necessary cannot work without doing this.
i tried passing in responsedata
parsexml()
function
parse_xml(responsedata)
and in function
tree = etree.parse(responsedata) fdtime = tree.xpath('//rsp/fd/fdtime/text()')
but doesn't work.
if want parse in-memory object (in case, string), use etree.fromstring(<obj>)
-- etree.parse
expects file-like object or filename -- docs
for example:
import urllib2, lxml.etree 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))
output:
<element note @ 0x2c29dc8> <note> <to>tove</to> <from>jani</from> <heading>reminder</heading> <body>don't forget me weekend!</body> </note>
Comments
Post a Comment