Python Requests package: handling an xml response

I really like the requests package and its convenient way to handle JSON responses.

Unfortunately, I did not understand if I can also process XML responses. Does anyone know how to handle XML responses with requests package? Do I need to include another package, for example urllib2 for decoding XML?

+96
python xml python-requests
Aug 19 '13 at 7:29
source share
1 answer

requests does not parse XML responses, no. XML responses are much more complex in nature than JSON responses, as you serialized XML data in Python structures is not so simple.

Python comes with built-in XML parsers. I recommend using the ElementTree API :

 import requests from xml.etree import ElementTree response = requests.get(url) tree = ElementTree.fromstring(response.content) 

or, if the answer is especially large, use the incremental approach:

 response = requests.get(url, stream=True) # if the server sent a Gzip or Deflate compressed response, decompress # as we read the raw stream: response.raw.decode_content = True events = ElementTree.iterparse(response.raw) for event, elem in events: # do something with `elem` 

The external lxml project is based on the same API, which gives you more options and power.

+167
Aug 19 '13 at 7:33
source share



All Articles