Save XML response from GET call using Python

邮差的信 提交于 2020-01-03 11:27:09

问题


I'm trying to create a realtime report using an API that allows me to grab the data I need and returns it in XML format. What I want to know is, after receiving the response, how can I save it to an .xml file locally? Or cache it, that way I can parse it before parsing the response.

import requests
r = requests.get('url',  auth=('user', 'pass'))

I'm using requests since it's the easiest way to make a GET call in my opinion. Also, this is my first question and I'm barely starting to learn Python, I'd appreciate it if you guys had a little patience. Thanks.

I was looking at a similar question but for JSON, not sure if it would work the same, https://stackoverflow.com/a/17519020/4821590

import requests
import json
solditems = requests.get('https://github.com/timeline.json') # (your url)
data = solditems.json()
with open('data.json', 'w') as f:
    json.dump(data, f)

回答1:


If you want to be able to parse the returned XML before doing stuff with it, the xml tree is your friend.

import requests
import xml.etree.ElementTree as ET

r = requests.get('url',  auth=('user', 'pass'))
tree = ET.parse(r.text)
root = tree.getroot()

Otherwise, as jordanm has commented, you could just save it to a file and be done with it.

with open('data.xml', 'w') as f:
    f.write(r.text)



回答2:


Few notes related to Python3 (at least 3.6 versions):

1) when using xml.etree.ElementTree with requests, you use fromstring not parse. r.text returns a string, and xml.etree.ElementTree.parse is for files

import requests
import xml.etree.ElementTree as ET

r = requests.get("https://xml.returning.uri")
root = ET.fromstring(r.text)

2) This creates an element object as the root (no more tree). So to write it back out, you'll need to make it a tree:

tree = ET.ElementTree(root)
tree.write("file.xml")

From the docs

xml.etree.ElementTree.parse(source, parser=None) Parses an XML section into an element tree. source is a filename or file object containing XML data.

xml.etree.ElementTree.fromstring(text) Parses an XML section from a string constant. Same as XML(). text is a string containing XML data. Returns an Element instance



来源:https://stackoverflow.com/questions/29810572/save-xml-response-from-get-call-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!