跳到正文

科技·工程

再见喵,洛谷

fkxr约 17 分钟
原文
文章信息与版本

文章信息

收录
2026年2月20日
更新
2026年4月5日
篇幅
约 17 分钟

版本

  1. v2当前
  2. v1

项目地址

简介

luogu_getter 是一个用于抓取并保存你在洛谷上的提交记录与代码的轻量 Python 脚本集合。

运行后将自动:

  • 获取指定用户的所有提交记录;
  • 保存每次提交的代码和对应 HTML 页面;
  • 以增量方式更新(已抓取过的数据不会重复抓取)。

⚠️ 本脚本仅用于合理合法的用途,请遵守洛谷平台使用协议,不要滥用爬虫对服务器造成压力。

功能

  • 获取并保存洛谷用户的提交记录;
  • 按提交分别下载代码与界面 HTML;
  • 增量抓取:已有数据不会重复请求;
  • 输出 {uid}.json 文件保存原始记录。

环境准备

请确保你已安装以下运行环境:

  • Python 3.6+
  • requests

可使用 pip 安装依赖:

Bash
pip install requests

使用方法

  1. 在 GitHub 获取 get_record.py 和 get_code.py。

  2. 在两个程序中填入你的 cookie\color{red}\textup{\textmd{在两个程序中填入你的 cookie}}

  3. 获取记录:

    Bash
    python ./get_record.py
  4. 下载代码:

    Bash
    python ./get_code.py

运行后会生成如下内容:

  • {uid}.json — 保存获取的全部提交记录;
  • code/ — 所有提交代码文件;
  • records/ — 各提交对应的网页 HTML。

工作逻辑

  • get_record.py:访问 https://www.luogu.com.cn/record/list?user={your uid},按用户 UID 获取所有提交记录;
  • get_code.py:读取记录 JSON,下载每次提交包含的代码;
  • 增量逻辑:只处理未保存过的记录以避免重复抓取。

示例输出结构

代码
.
├── 123456.json
├── code
│   ├── R12345_Pxxxx.cpp
│   ├── R19345_Uxxxxx.cpp
│   └── R23456_Bxxxx.py
└── records
    ├── R12345.html
    ├── R19345.html
    └── R23456.html

注意事项

  • 不要滥用脚本对洛谷服务器产生压力;
  • 如果脚本运行失败,请检查是否填入 cookie,并调高爬取间隔;
  • 本项目 Star 越多越有动力更新。

Star History Chart

最后

本项目不足之处:

  • 在 get_code.py 中,mapping 语言映射可能不准确,如果你是大手子,可以给我的项目发 Issue 或者用其他方式联系我。
  • 待补充

如果你因为某些众所周知的原因无法访问 GitHub,可以用下面的代码(不保证会更新):

就是一个折叠框啦

get_record.py:

Python
import requests
import json
import time
import os
import re
from urllib.parse import unquote

# 配置保持不变
USER_ID = "Your uid"  # 重要! # ---------------------------------------------------------
URL_BASE = f"https://www.luogu.com.cn/record/list?user={USER_ID}&page="
FILE_NAME = f"{USER_ID}.json"
COOKIES = {
    "__client_id": "Your cookie", # 重要! # ---------------------------------------------
    "_uid": USER_ID
}
HEADERS = {
    "User-Agent": "Chtholly Nota Senioriou",# 彩蛋喵
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Referer": "https://www.luogu.com.cn/"
}

def extract_json_from_html(html_text):
    """从 HTML 中提取 window._feInjection 里的 JSON 数据"""
    # 正则定位:匹配 window._feInjection = JSON.parse(decodeURIComponent("...")) 内部的内容
    pattern = r'window\._feInjection = JSON\.parse\(decodeURIComponent\("(.+?)"\)\);'
    match = re.search(pattern, html_text)
    if match:
        encoded_json = match.group(1)
        # 解码 URL 编码并转为 Python 字典
        return json.loads(unquote(encoded_json))
    return None

def crawl():
    # 读取本地已有的提交 ID (逻辑同前)
    local_data = []
    if os.path.exists(FILE_NAME):
        with open(FILE_NAME, 'r', encoding='utf-8') as f:
            local_data = json.load(f)

    latest_id = local_data[0]['id'] if local_data else None
    new_records = []
    page = 1

    while True:
        print(f"正在抓取第 {page} 页...")
        try:
            response = requests.get(f"{URL_BASE}{page}", headers=HEADERS, cookies=COOKIES, timeout=10)
            res_data = extract_json_from_html(response.text)

            if not res_data:
                print("解析 HTML 数据失败,可能是模板已更改或被反爬拦截。")
                break

            records = res_data.get("currentData", {}).get("records", {}).get("result", [])

            if not records:
                print("抓取完毕或当前页无数据。")
                break

            stop_found = False
            for item in records:
                if latest_id and item['id'] == latest_id:
                    print(f"到达本地存量数据位置 (ID: {latest_id}),停止抓取。")
                    stop_found = True
                    break

                # 按照你的本地 {uid}.json 格式精简字段
                new_records.append({
                    "time": item.get("time"),
                    "memory": item.get("memory"),
                    "problem": item.get("problem"),
                    "contest": item.get("contest"),
                    "sourceCodeLength": item.get("sourceCodeLength"),
                    "submitTime": item.get("submitTime"),
                    "language": item.get("language"),
                    "id": item.get("id"),
                    "status": item.get("status"),
                    "enableO2": item.get("enableO2"),
                    "score": item.get("score")
                })

            if stop_found:
                break

            page += 1
            time.sleep(3)

        except Exception as e:
            print(f"发生异常: {e}")
            break

    # 合并并保存
    if new_records:
        final_data = new_records + local_data
        with open(FILE_NAME, 'w', encoding='utf-8') as f:
            json.dump(final_data, f, ensure_ascii=False, indent=4)
        print(f"更新成功!新增 {len(new_records)} 条,总计 {len(final_data)} 条。")
    else:
        print("没有新记录需要更新。")

if __name__ == "__main__":
    crawl()

get_code.py:

Python
import requests
import time
import re
import json
from pathlib import Path
from urllib.parse import unquote

# === 配置区 ===
USER_ID = "Your uid"  # 重要! # ---------------------------------------------------------
URL_BASE = "https://www.luogu.com.cn/record/"
INPUT_FILE = Path(f"{USER_ID}.json")  # 你的上一步产物
COOKIES = {
    "__client_id": "Your cookie", # 重要! # ---------------------------------------------
    "_uid": USER_ID
}
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Referer": "https://www.luogu.com.cn/"
}

# 路径配置
RECORDS_DIR = Path('records')
CODE_DIR = Path('code')

# 使用 pathlib 优雅地创建文件夹
# https://github.com/shtian-fkxr/luogu_getter/issues/1
RECORDS_DIR.mkdir(parents=True, exist_ok=True)
CODE_DIR.mkdir(parents=True, exist_ok=True)

def get_extension_by_lang(lang_id):
    """根据洛谷语言 ID 返回后缀名"""
    mapping = {
        0: ".cpp", 1: ".py", 2: ".c", 3: ".cpp", 4: ".cpp",
        7: ".py", 8: ".py", 11: ".cpp", 12: ".cpp", 13: ".java",
        14: ".pas", 16: ".php", 20: ".php", 22: ".py", 25: ".py",
        26: ".cpp", 27: ".cpp", 28: ".cpp", 34: ".cpp"
    }
    return mapping.get(lang_id, ".txt")

def process_record(rid, html_content):
    """解析详情页 HTML 并提取源代码"""
    pattern = re.compile(r'window\._feInjection = JSON\.parse\(decodeURIComponent\("(.+?)"\)\);')
    match = pattern.search(html_content)
    if not match:
        return False

    try:
        data = json.loads(unquote(match.group(1)))
        record = data.get('currentData', {}).get('record', {})
        source_code = record.get('sourceCode')
        lang_id = record.get('language')

        if source_code:
            ext = get_extension_by_lang(lang_id)
            pid = record.get('problem', {}).get('pid', 'Unknown')
            code_filename = f"R{rid}_{pid}{ext}"
            code_path = CODE_DIR / code_filename # 路径拼接更直观

            code_path.write_text(source_code, encoding='utf-8')
            return True
    except Exception as e:
        print(f"\n[Error] 解析 R{rid} 失败: {e}")
    return False

# 1. 从你的 JSON 文件读取 ID
if not INPUT_FILE.exists():
    print(f"找不到文件 {INPUT_FILE},请先运行 get_record。")
    exit()

history_data = json.loads(INPUT_FILE.read_text(encoding='utf-8'))

# 提取所有提交 ID
ids = [item['id'] for item in history_data]
print(f"同步到本地记录: {len(ids)} 条")

# 2. 循环爬取详情
for i, rid in enumerate(ids):
    html_path = RECORDS_DIR / f"R{rid}.html"

    print(f"进度 [{i+1}/{len(ids)}] - 正在处理 R{rid}...", end='\r')

    # A: 本地缓存处理
    if html_path.exists():
        process_record(rid, html_path.read_text(encoding='utf-8'))
        continue

    # B: 发起网络请求
    try:
        response = requests.get(f"{URL_BASE}{rid}", headers=HEADERS, cookies=COOKIES, timeout=10)

        if response.status_code == 200:
            html_text = response.text
            # 保存 HTML 备份
            html_path.write_text(html_text, encoding='utf-8')

            if process_record(rid, html_text):
                time.sleep(3)
            else:
                print(f"\n[Error] R{rid} 无法提取代码")
        elif response.status_code == 404:
             print(f"\n[Error] R{rid} 不存在 (404)")
        else:
            print(f"\n[Error] R{rid} 状态码: {response.status_code}")
            time.sleep(5)

    except Exception as e:
        print(f"\n[Error] R{rid}: {e}")
        time.sleep(5)

print("\n\n所有源代码已同步至 /code 文件夹!")
AI 使用说明

本项目代码在完成之后使用 Gemini 3 Thinking 优化码风。

README.md 和本文用 Gemini 3 Thinking 润色。

原文