Python Requests package: Handling xml response

后端 未结 1 1318
小蘑菇
小蘑菇 2020-11-28 04:38

I like very much the requests package and its comfortable way to handle JSON responses.

Unfortunately, I did not understand if I can also process XML r

相关标签:
1条回答
  • 2020-11-28 04:45

    requests does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.

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

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

    or, if the response is particularly large, use an 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 builds on the same API to give you more features and power still.

    0 讨论(0)
提交回复
热议问题