Python 请求包:处理 xml 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18308529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:27:07  来源:igfitidea点击:

Python Requests package: Handling xml response

pythonxmlhttprequestpython-requests

提问by Andy

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

我非常喜欢这个requests包及其处理 JSON 响应的舒适方式。

Unfortunately, I did not understand if I can also process XML responses. Has anybody experience how to handle XML responses with the requestspackage? Is it necessary to include another package for the XML decoding?

不幸的是,我不明白我是否也可以处理 XML 响应。有没有人体验过如何使用requests包处理 XML 响应?是否需要包含另一个用于 XML 解码的包?

回答by Martijn Pieters

requestsdoes 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.

requests不处理解析 XML 响应,不。XML 响应本质上比 JSON 响应复杂得多,如何将 XML 数据序列化为 Python 结构并不那么简单。

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

Python 带有内置的 XML 解析器。我建议您使用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 projectbuilds on the same API to give you more features and power still.

外部lxml 项目构建在相同的 API 上,为您提供更多功能和功能。