Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从API调用访问数字数据?_Python_Api_Python Requests - Fatal编程技术网

Python 如何从API调用访问数字数据?

Python 如何从API调用访问数字数据?,python,api,python-requests,Python,Api,Python Requests,我正在通过API调用访问芝加哥商品交易所的期货价格数据 我正在使用一个URL,当我在浏览器中发布它时,它会返回一个csv文件(gzip压缩)。然而,我确实需要用python编写一个程序,可以接收数千个URL并处理它接收到的数据。在python中的requests.get()命令中使用此URL时,会得到一个我不知道如何读取的响应 import requests url='https://datamine.cmegroup.com/cme/api/v1/download?fid=20181211-

我正在通过API调用访问芝加哥商品交易所的期货价格数据

我正在使用一个URL,当我在浏览器中发布它时,它会返回一个csv文件(gzip压缩)。然而,我确实需要用python编写一个程序,可以接收数千个URL并处理它接收到的数据。在python中的requests.get()命令中使用此URL时,会得到一个我不知道如何读取的响应

import requests

url='https://datamine.cmegroup.com/cme/api/v1/download?fid=20181211- 
EOD_xcbt_ff_fut_0-eth_p'
user = '***'
password = '***'

r = requests.get(url, auth=(user, password))
print(r.headers)
除其他事项外,还包括:

{
    'Date': 'Sun, 30 Dec 2018 13:01:07 GMT',
    'Content-Type': 'application/x-gzip',
    'Content-Length': '1287',
    'Content-disposition': 'attachment; filename="xcbt-eodp-ff-fut-20181211.csv.gz"'
}
我假设我试图获得的价格包含在元素
附件中;filename=“xcbt-eodp-ff-fut-20181211.csv.gz”

我的问题:

我如何从收到的回复中获得价格? 那么,如何将数据导入到
数据帧中

简单地使用:

print(r.content)

不返回数值

您应该做如下操作:

resp = requests.get(url)

# for now it's a Response object. Make a json out of it
json_resp = resp.json()

print(json_resp.get('some_key')) # or what ever you need

然后使用简单的dict功能提取所需内容。

请查看。您需要使用
r.text
r.json()
。看起来API并没有返回准确的数据,而是返回gziped CSV的文件名。您需要首先解压缩文件,然后将CSV加载到python中,这样您就可以读取各个字段。根据数据量的不同,您可能希望第一个脚本处理API查询并下载
csv.gz
文件以解压缩它们,然后第二个脚本读取csv文件(从本地磁盘)并对数据进行进一步分析。