我想从这个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
最佳答案
由于您没有在请求中指定所需的货币对,因此 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'])
关于python - 无法从使用 json 的 URL api 获取信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651961/