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

如何从Codeforces API获取可用的Pandas DataFrame?

解决Codeforces API数据获取与分析问题

问题根源

你直接用pd.read_csv()读取Codeforces API地址是错误的——Codeforces API返回的是JSON格式数据,不是CSV,这才导致生成了无效的0行DataFrame。

正确获取比赛列表数据的代码

先使用requests库获取API返回的JSON,再提取核心数据转为Pandas DataFrame:

import pandas as pd
import requests

# 请求比赛列表API(排除gym赛事)
response = requests.get("https://codeforces.com/api/contest.list?gym=false")
data = response.json()

# 检查API响应状态,提取result部分转为DataFrame
if data["status"] == "OK":
    contest_df = pd.DataFrame(data["result"])
else:
    print(f"API请求失败:{data.get('comment', '未知错误')}")

# 查看前5条数据验证
print(contest_df.head())

这段代码会生成包含所有公开比赛信息的有效DataFrame,包含比赛ID、名称、开始时间、参赛人数等字段,满足基础的赛事轮次分析需求。

获取参与者与分数数据(满足分数/分数变化分析)

要分析参与者分数、分数变化,需要调用contest.standings API,示例代码如下:

def get_contest_standings(contest_id):
    # 请求指定比赛的排名数据
    response = requests.get(f"https://codeforces.com/api/contest.standings?contestId={contest_id}&from=1&count=1000")
    data = response.json()
    if data["status"] != "OK":
        print(f"获取比赛{contest_id}数据失败:{data.get('comment')}")
        return None
    
    # 提取选手排名数据
    standings = data["result"]["rows"]
    # 构造选手信息+分数的DataFrame
    standings_data = []
    for row in standings:
        user_info = row["party"]["members"][0]
        standings_data.append({
            "contest_id": contest_id,
            "user_id": user_info["handle"],
            "rank": row["rank"],
            "total_score": row["points"],
            "max_rating": user_info.get("maxRating"),
            "current_rating": user_info.get("rating")
        })
    return pd.DataFrame(standings_data)

# 示例:获取某场比赛(比如ID=1800)的排名数据
standings_df = get_contest_standings(1800)
print(standings_df.head())

通过遍历你需要分析的比赛ID,就能批量获取所有参赛选手的分数、排名、评级变化等数据。

导出数据到Excel/SQL

导出到Excel

# 导出比赛列表到Excel
contest_df.to_excel("codeforces_contests.xlsx", index=False)
# 导出选手排名数据到Excel
standings_df.to_excel("contest_1800_standings.xlsx", index=False)

导出到SQL(以MySQL为例)

需要先安装sqlalchemy和pymysql库,然后执行:

from sqlalchemy import create_engine

# 创建数据库连接(替换为你的数据库信息)
engine = create_engine("mysql+pymysql://用户名:密码@localhost:3306/codeforces_data")

# 将DataFrame写入SQL表
contest_df.to_sql("contests", engine, if_exists="replace", index=False)
standings_df.to_sql("contest_standings", engine, if_exists="append", index=False)

注意事项

  • Codeforces API有调用频率限制:1秒最多1次请求,1分钟最多60次,超出会被临时封禁IP,批量请求时记得加延时(比如time.sleep(1))。
  • 部分API接口需要用户登录(比如获取私人比赛数据),但公开赛事数据无需登录即可获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 18:25:38