Python 请求包:处理 xml 响应 [英] Python Requests package: Handling xml response

查看:34
本文介绍了Python 请求包:处理 xml 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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 带有内置的 XML 解析器.我建议您使用 ElementTree API:

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`

外部 lxml 项目基于相同的 API 构建,为您提供更多功能和功能.

The external lxml project builds on the same API to give you more features and power still.

这篇关于Python 请求包:处理 xml 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆