调用Poke API批量获取宝可梦数据时遇JSONDecodeError求助
问题分析与解决
批量请求Poke API时出现json.decoder.JSONDecodeError,但单个请求正常,核心原因是短时间内频繁触发API限流机制,服务器返回了非JSON格式的响应(比如429 Too Many Requests的页面内容),导致JSON解析失败。
修复方案
- 添加请求延迟:避免短时间内大量请求触发限流
- 检查响应状态码:确保请求成功后再解析数据
- 使用requests内置的JSON解析方法:简化代码并获得更明确的错误提示
- 添加异常捕获:避免单个请求失败导致整个程序崩溃
修改后的代码
import requests import pandas as pd import time pokemon_list = ["charizard", "gengar", "venusaur","golbat","gyarados","lapras", "dragonite", "infernape", "staraptor", "giratina"] name, height, weight = [],[],[] for pokemon in pokemon_list: try: res = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}/") # 检查请求是否成功 res.raise_for_status() # 使用requests内置的json方法解析 pokedata = res.json() name.append(pokedata["name"]) height.append(pokedata["height"]) weight.append(pokedata["weight"]) # 添加1秒延迟,避免限流 time.sleep(1) except requests.exceptions.RequestException as e: print(f"请求{pokemon}失败: {e}") except KeyError as e: print(f"解析{pokemon}数据失败,缺少字段: {e}") ddata = {"Name": name, "Height": height, "Weight": weight} df_data = pd.DataFrame(ddata) print(df_data)
关键改进点说明
res.raise_for_status():如果请求返回4xx/5xx状态码,会直接抛出异常,避免解析无效内容res.json():替代json.loads(res.text),内部已处理响应编码和格式检查,出错时抛出更清晰的异常time.sleep(1):每次请求后暂停1秒,符合Poke API的限流要求(官方建议避免超过100请求/分钟)- 异常捕获:分别处理请求错误和数据解析错误,方便排查问题
内容的提问来源于stack exchange,提问作者Jalfred
相关产品推荐
相关产品推荐

