pythonxmlpython-requestsxml-parsingsave

Save XML response from GET call using Python


How can I save XML API response to an .xml files? Or cache it, that way I can parse it before parsing the response.

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

I looked at a similar question for JSON: 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)

Solution

  • 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)