跳到正文

科技·工程

【爬虫】洛谷模拟登录

maxflow约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月22日
篇幅
约 5 分钟

版本

  1. v1当前

刑

本文使用 python3 的爬虫 + Ddddocr 验证码识别实现洛谷模拟登录。

先实现验证码识别。

Python
import requests
import ddddocr

from PIL import Image

from .constants import *

ocr = ddddocr.DdddOcr(show_ad=False)
ocr.set_ranges(6)


def recognize(session: requests.Session, url: str, debug: bool = False) -> str:
    response = session.get(url, headers=HEADERS)
    if response.status_code != 200:
        raise ValueError(response.status_code)
    res = ocr.classification(response.content)
    if debug:
        with open(CAPTCHA_DEBUG_PATH, 'wb') as f:
            f.write(response.content)
        with Image.open(CAPTCHA_DEBUG_PATH) as img:
            img.show()
        print(f'识别结果: {res}')
    return res

这里给出 constants 库的常量。

Python
CAPTCHA_DEBUG_PATH = 'captcha.jfif'

INDEX_URL = 'https://www.luogu.com.cn/'

LOGIN_CAPTCHA_URL = 'https://www.luogu.com.cn/lg4/captcha'
LOGIN_URL = 'https://www.luogu.com.cn/do-auth/password'
LOGIN_RETRIES = 5

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                  '(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
}
PROBLEM_SUBMIT_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                  '(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Content-Type': 'application/json',
}

实现模拟登录:

Python
import time
import random

import requests

from .captcha import recognize
from .constants import *


def login(username: str, password: str) -> requests.Session:
    session = requests.Session()
    session.get(INDEX_URL, headers=HEADERS)
    data = {
        'username': username,
        'password': password,
        'captcha': recognize(session, LOGIN_CAPTCHA_URL)
    }
    response = session.post(LOGIN_URL, data=data, headers=HEADERS)
    retry_cnt = 0
    while response.status_code != 200:
        retry_cnt += 1
        if retry_cnt > LOGIN_RETRIES:
            raise ValueError('重试次数达到上限,可能是用户名或密码不正确')
        data['captcha'] = recognize(session, LOGIN_CAPTCHA_URL)
        time.sleep(random.uniform(0.1, 0.2))
        response = session.post(LOGIN_URL, data, headers=HEADERS)
    return session

刑

原文