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

2024-10-02 14:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从以下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

Tags: httpsimportcomapi信息urlbinance符号
1条回答
网友
1楼 · 发布于 2024-10-02 14:29:18

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

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

因此,您要么只需要请求所需配对的详细信息,要么在已获取的列表中找到所需配对的详细信息

要仅请求所需的对,请将请求的URL参数as an argument用于get请求:

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'])

相关问题 更多 >