无法从使用json的URL API获取信息?

时间:2019-10-31 22:32:17

标签: python json api dictionary binance

我想从此URL获取api信息: https://api.binance.com/api/v1/ticker/24hr 我需要告诉一个符号(ETHBTC)并获取最新价格。

import requests

binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
e = binance.json()
print(e['ETHBTC']['lastPrice'])

错误:

Traceback (most recent call last):
  File "C:\Users\crist\Documents\Otros\Programacion\Python HP\borrar.py", line 6, in <module>
    print(e['ETHBTC']['lastPrice'])
TypeError: list indices must be integers or slices, not str

1 个答案:

答案 0 :(得分:0)

由于您没有在请求中指定所需的货币对,因此Binance API将返回列表中所有货币对的详细信息,如下所示:

[
    { Pair 1 info },
    { Pair 2 info },
    { etc.        }
]

因此,您只需要请求所需对的详细信息,或者在已经获取的列表中找到所需对的详细信息即可。

要仅请求所需的一对,请对get请求使用请求的URL参数as an argument

myparams = {'symbol': 'ETHBTC'}
binance = requests.get("https://api.binance.com/api/v1/ticker/24hr", params=myparams)
e = binance.json()
print(e['lastPrice'])

或者,要在已获取的列表中找到所需的对,可以遍历列表。除非您想查看很多不同的货币对,否则第一个选择就是方法。

binance = requests.get("https://api.binance.com/api/v1/ticker/24hr")
e = binance.json()
for pair in e:
    if pair['symbol'] == 'ETHBTC':
        print(pair['lastPrice'])