You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法获取返回的玩家统计数据?技术问题咨询

问题排查与修复方案

以下是导致你无法获取统计数据的常见原因及对应修复方法:

1. 未处理API请求失败场景

你的代码直接从响应中提取数据,但未考虑请求失败的情况(比如玩家名不存在、网络故障、API限流),一旦请求出错就会抛出异常中断执行。

修复:添加状态码检查与异常捕获:

response = requests.get(url)
if response.status_code != 200:
    print(f"获取玩家{player}UUID失败,状态码:{response.status_code}")
    continue
try:
    uuid = response.json()['id']
except KeyError:
    print(f"玩家{player}不存在,API未返回UUID")
    continue

2. Hypixel API请求未做有效性校验

Hypixel API可能返回错误(比如API密钥无效、玩家无Bedwars数据),直接提取bedwars_level会触发KeyError。

修复:校验API响应的success状态,捕获数据缺失异常:

hypixel_response = requests.get(requestlink)
if hypixel_response.status_code != 200:
    print(f"获取玩家{player}Hypixel数据失败,状态码:{hypixel_response.status_code}")
    continue
hydata = hypixel_response.json()
if not hydata.get('success'):
    print(f"Hypixel API错误:{hydata.get('cause', '未知错误')}")
    continue
try:
    level = int(hydata['achievements']['bedwars_level'])
except KeyError:
    print(f"玩家{player}无Bedwars等级数据")
    continue

3. 缺失必要依赖与变量定义

代码中使用了os和requests模块但未导入,且api_key未赋值,queue可能为空。

修复:

  • 在代码开头添加导入语句:
    import os
    import requests
    
  • 给api_key赋值为有效的Hypixel API密钥,确保queue填充了玩家名称。

修复后的完整代码

import os
import requests

# 替换为实际玩家列表
queue = ["ExamplePlayer1", "ExamplePlayer2"]
# 替换为你的Hypixel API密钥
api_key = "your-hypixel-api-key"
player_list = {}

def update_stats():
    os.system("cls")
    for player in queue:
        # 获取玩家UUID
        url = f'https://api.mojang.com/users/profiles/minecraft/{player}'
        response = requests.get(url)
        if response.status_code != 200:
            print(f"获取玩家{player}UUID失败,状态码:{response.status_code}")
            continue
        try:
            uuid = response.json()['id']
        except KeyError:
            print(f"玩家{player}不存在,API未返回UUID")
            continue
        
        # 获取Hypixel玩家数据
        requestlink = f"https://api.hypixel.net/player?key={api_key}&uuid={uuid}"
        hypixel_response = requests.get(requestlink)
        if hypixel_response.status_code != 200:
            print(f"获取玩家{player}Hypixel数据失败,状态码:{hypixel_response.status_code}")
            continue
        hydata = hypixel_response.json()
        if not hydata.get('success'):
            print(f"Hypixel API错误:{hydata.get('cause', '未知错误')}")
            continue
        
        # 提取Bedwars等级
        try:
            level = int(hydata['achievements']['bedwars_level'])
            player_list[player] = [str(level)]
        except KeyError:
            print(f"玩家{player}无Bedwars等级数据")
            continue
    print(player_list)

update_stats()

内容的提问来源于stack exchange,提问作者Riyan Nayak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:33:32