使用Python保存来自GET调用的XML响应 [英] Save XML response from GET call using Python

查看:262
本文介绍了使用Python保存来自GET调用的XML响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用API​​创建实时报告,该API允许我获取所需的数据并以XML格式返回.我想知道的是,收到响应后,如何将其保存到本地的.xml文件中?或缓存它,这样我就可以在解析响应之前对其进行解析.

I'm trying to create a realtime report using an API that allows me to grab the data I need and returns it in XML format. What I want to know is, after receiving the response, how can I save it to an .xml file locally? Or cache it, that way I can parse it before parsing the response.

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

我正在使用请求,因为我认为这是拨打GET呼叫的最简单方法.另外,这是我的第一个问题,我几乎还没有开始学习Python,如果你们有一点耐心,我将不胜感激.谢谢.

I'm using requests since it's the easiest way to make a GET call in my opinion. Also, this is my first question and I'm barely starting to learn Python, I'd appreciate it if you guys had a little patience. Thanks.

我正在寻找一个类似的问题,但是对于JSON,不确定它是否可以正常工作, https://stackoverflow.com/a/17519020/4821590

I was looking at a similar question but for JSON, not sure if it would work the same, 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)

推荐答案

如果您希望能够在处理返回的XML之前对其进行解析,则

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

否则,正如jordanm所说,您可以将其保存到文件中并完成操作.

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)

这篇关于使用Python保存来自GET调用的XML响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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