调用地震API时触发KeyError: 'result',寻求解决方法
解决KeyError: 'result'问题
问题根源
你的代码直接假设API返回的JSON里一定包含result字段,但实际请求可能因为请求方式错误、API返回格式变更或者服务器错误,导致返回的JSON没有这个字段,触发KeyError。
分步解决方案
1. 先确认API返回的实际内容
首先修改代码,打印出API返回的完整JSON,搞清楚真实的返回结构:
# 替换原来的请求代码 response = requests.post("https://api.orhanaydogdu.com.tr/deprem/live.php") print("API返回内容:", response.json()) # 打印返回的JSON数据 data = response.json()
运行后查看控制台输出,就能明确API到底返回了什么——比如可能是错误信息,或者字段名已经改变。
2. 修正请求方式(大概率是核心问题)
很多公开地震数据API只接受GET请求,你当前用的是POST,尝试改成GET:
response = requests.get("https://api.orhanaydogdu.com.tr/deprem/live.php") data = response.json()
3. 避免覆盖内置模块,添加异常防护
- 不要用
json作为变量名,你已经导入了json模块,这样会覆盖模块引用,改成data或者response_json。 - 添加请求状态检查和字段存在性判断,防止程序崩溃:
import json from os import system from time import sleep import requests from colorama import init, Fore init(autoreset=True) while True: print(Fore.RED+" 5 1 2 4 - O f f i c a l \n") print(Fore.RED+"Tür "+Fore.CYAN+"Tarih & Saat "+Fore.GREEN+"Yer "+Fore.RED+"Büyüklük "+Fore.YELLOW+"Derinlik") print("-------------------------------------------------------------------------------") try: response = requests.get("https://api.orhanaydogdu.com.tr/deprem/live.php") response.raise_for_status() # 捕获HTTP错误(比如404、500) data = response.json() # 检查result字段是否存在 if "result" not in data: print(Fore.YELLOW + "警告:API返回数据格式异常,未找到'result'字段") print("当前返回内容:", data) else: for item in data["result"]: tarih = item["date"] yer = item["lokasyon"] büyüklük = item["mag"] derinlik = item["depth"] print(Fore.RED+"Deprem ! "+Fore.CYAN+tarih+Fore.GREEN+" "+yer+Fore.RED+" "+str(büyüklük)+Fore.YELLOW+" "+str(derinlik)) except requests.exceptions.RequestException as e: print(Fore.RED + f"请求出错:{str(e)}") except KeyError as e: print(Fore.RED + f"数据字段缺失:{str(e)}") sleep(13) system("cls") sleep(0.6)
4. 应对API结构变更
如果打印后发现API返回的结构已经改变(比如用data代替了result),只需要把代码中data["result"]改成对应的字段名即可。
内容的提问来源于stack exchange,提问作者Snowflake
相关产品推荐
相关产品推荐

