如何用For循环+If语句筛选Steam API返回的多人合作游戏至列表
解决Steam API获取多人/合作游戏列表的问题
原代码存在的问题
- 未初始化
multiplayer_games列表,直接调用append会触发NameError - 调用steamapis接口后,未解析响应JSON,
tags和app_name变量未定义,逻辑断裂 - 筛选条件仅判断"Multi-player",未覆盖"Co-op"等目标标签
- 未处理API请求失败的异常情况(如网络错误、无效响应)
- 未实现将已购游戏转换为
{AppID: 游戏名}字典的需求
修正后的完整代码
import requests # 初始化必要变量 steam_key = "你的Steam API密钥" steam_id = "目标用户SteamID" multiplayer_games = [] # 1. 获取已购游戏并转换为{AppID: 游戏名}的字典 try: oresponse = requests.get( f"https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={steam_key}&steamid={steam_id}&format=json&include_appinfo=1" ) oresponse.raise_for_status() # 检查请求是否成功 owned_games = oresponse.json() # 生成AppID为键、游戏名为值的字典 appid_to_name = {game["appid"]: game["name"] for game in owned_games["response"]["games"]} except requests.exceptions.RequestException as e: print(f"获取已购游戏失败: {e}") exit() # 2. 遍历每个AppID,筛选多人/合作游戏 target_tags = {"Multi-player", "Co-op", "Online Co-op", "Local Co-op"} # 扩展需要的标签 for appid, app_name in appid_to_name.items(): try: mresponse = requests.get( f"https://api.steamapis.com/market/app/{appid}?api_key={steam_key}" ) mresponse.raise_for_status() app_details = mresponse.json() # 提取标签列表,处理可能的键缺失情况 tags = app_details.get("data", {}).get("tags", []) # 检查是否包含目标标签 if any(tag.get("description") in target_tags for tag in tags): multiplayer_games.append(app_name) except requests.exceptions.RequestException as e: print(f"获取游戏{app_name}(ID:{appid})详情失败: {e}") continue # 输出结果 print("多人/合作游戏列表:") for game in multiplayer_games: print(f"- {game}")
关键修正说明
- 添加
include_appinfo=1参数:Steam的GetOwnedGames接口默认不返回游戏名称,必须加这个参数才能获取name字段 - 初始化
multiplayer_games空列表,避免未定义错误 - 加入异常处理:捕获网络请求错误,避免程序崩溃
- 扩展目标标签集合:覆盖"Co-op"等多种合作/多人标签
- 处理键缺失情况:使用
.get()方法避免因响应结构变化导致的KeyError - 实现
{AppID: 游戏名}字典:满足最初的格式转换需求
内容的提问来源于stack exchange,提问作者Jared Robertson
相关产品推荐
相关产品推荐

