Python调用CoinGecko API获比特币价格时遇KeyError: 'bitcoin'求助
解决获取加密货币实时价格时的KeyError问题
问题详情
运行Python代码获取比特币实时价格时触发以下错误:
Traceback (most recent call last):
File "C:\Users\Rosemary Asante\PycharmProjects\pythonProject21\main.py", line 38, in
current_price = get_price('bitcoin')
File "C:\Users\Rosemary Asante\PycharmProjects\pythonProject21\main.py", line 34, in get_price
return Decimal(data[crypto]['usd'])
KeyError: 'bitcoin'
当前使用的代码如下:
import time import requests import urllib.parse import hashlib import hmac import base64 from decimal import Decimal def get_price(crypto): response = requests.get(f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd") data = response.json() return Decimal(data[crypto]['usd']) previous_price = None while True: current_price = get_price('bitcoin') if previous_price is not None: if current_price > previous_price: print("The price of Bitcoin went up.") elif current_price < previous_price: print("The price of Bitcoin went down.") else: print("The price of Bitcoin stayed the same.") previous_price = current_price
解决方案
1. 排查API响应内容
KeyError说明返回的data字典中不存在'bitcoin'键,大概率是API返回了异常数据。先在get_price函数中添加打印语句,查看实际响应:
def get_price(crypto): response = requests.get(f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd") print("API响应内容:", response.json()) # 新增此行查看响应结构 data = response.json() return Decimal(data[crypto]['usd'])
常见触发原因:
- 请求频率过高触发CoinGecko API限流,返回错误信息而非价格数据
- 网络波动导致请求失败,返回空字典或非预期格式
2. 添加异常处理与重试逻辑
针对API请求失败、响应异常的情况,增加异常捕获和重试机制,提升代码稳定性:
def get_price(crypto): max_retries = 3 for attempt in range(max_retries): try: response = requests.get(f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies=usd") response.raise_for_status() # 主动触发HTTP错误(如429限流、500服务器错误) data = response.json() # 验证数据结构是否符合预期 if crypto not in data or 'usd' not in data[crypto]: raise ValueError(f"未获取到{crypto}的有效价格数据") return Decimal(data[crypto]['usd']) except (requests.exceptions.RequestException, ValueError) as e: print(f"获取价格失败(第{attempt+1}/{max_retries}次尝试):{str(e)}") time.sleep(2) # 重试前等待2秒,避免频繁请求 raise Exception(f"经过{max_retries}次尝试后,仍无法获取{crypto}的价格")
3. 控制请求频率
CoinGecko免费API有限流规则(通常每分钟最多50-100次请求),你的代码是无限循环无间隔请求,极易触发限流。在循环中添加延迟:
while True: current_price = get_price('bitcoin') # 价格判断逻辑 if previous_price is not None: if current_price > previous_price: print("比特币价格上涨了。") elif current_price < previous_price: print("比特币价格下跌了。") else: print("比特币价格保持不变。") previous_price = current_price time.sleep(10) # 每10秒请求一次,避免触发限流
4. 确认币种ID正确性
确保传入的crypto参数是CoinGecko API要求的正确ID(比特币为bitcoin、以太坊为ethereum),如果后续添加其他币种,需提前确认对应币种的正确ID。
内容的提问来源于stack exchange,提问作者Kellen Rippin
相关产品推荐
相关产品推荐

