Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5
547 字
3 分钟
用 Python 爬取 C++ 评测网站的题干和代码
2025-06-19
统计加载中...

前言#

最近不是特别忙的,看到闲置的 C/C++ 课本想起来我程序设计(C/C++)的代码没存档,于是想找个办法存一下。

实操#

要爬自己的代码首先要有自己的登录状态,一般在 cookie 里面,登录后在 network 下找到 cookie 复制下来,写一个请求头。

headers = {
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
'cookie': 'your cookie'
}

按章爬取代码#

观察到一共只有七章,规模不大,网页是动态网页不太好处理,于是我选择了折中的办法,手动打开每章的题目页,再用脚本爬。

开始之前需要先建个文件夹存爬下来的代码

name = 'your chapter name'
url = 'your url'
dir = Path.cwd() / 'codes' / name
dir.mkdir(parents=True, exist_ok=True)

把每一章的题展开到一页,观察每个题目的 div,大致结构如下

<div class="formulation">
题干...
<table>
<tr><td>输入</td><td>输出</td></tr>
<tr><td>第一组输入...</td><td>第一组输出……</td></tr>
<tr><td>第二组输入...</td><td>第二组输出……</td></tr>
...
</table>
<textarea class="coderunner-answer">
代码...
</textarea>
</div>

所以我们先 get 一下网页,用 BeautifulSoup 解析一下,find 全部的 formulation 各自处理

def crawl_code(dir, url):
res = requests.get(url, headers=headers)
soup = BS(res.content, 'lxml')
dir.mkdir(parents=True, exist_ok=True)
for idx, problem in enumerate(soup.find_all('div', class_='formulation')):
# 本来想转 markdown 的,但是观察到题面太不规范了,没有固定结构,所以干脆直接输出文本得了……
convert_formulation_to_text(problem, dir / f'problem_{idx + 1}.txt')

处理代码的函数我直接复制了一个 class 为 formulation 的 div 给 GPT 写了,随后微调了一下

def convert_formulation_to_text(formulation: Tag, output_path: Path):
md_lines = []
# ---- 正文文本(跳过表格) ----
for tag in formulation.find_all(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'div'], recursive=True):
# 跳过包含表格的 div/p
if tag.find('table'):
continue
text = tag.get_text(strip=True, separator=' ')
if text:
md_lines.append(text)
# ---- 表格样例处理 ----
table = formulation.find('table')
if table:
for row in table.find_all('tr')[1:]: # 跳过表头
cells = row.find_all('td')
if len(cells) >= 2:
input_text = cells[0].get_text(strip=True)
output_text = cells[1].get_text(strip=True)
md_lines.append(f"\n输入:\n{input_text}\n\n输出:\n{output_text}")
# ---- 代码块 ----
textarea = formulation.find('textarea', class_='coderunner-answer')
if textarea:
code = (
textarea.text
.replace('&lt;', '<')
.replace('&gt;', '>')
.replace('&amp;', '&')
.strip()
)
md_lines.append(code)
# ---- 写入文件 ----
output_path.write_text('\n'.join(md_lines), encoding='utf-8')

随后只需要手动改 name 和 url 就可以爬下来每章的代码啦😋

用 Python 爬取 C++ 评测网站的题干和代码
https://starlab.top/posts/cr-cpp/
作者
Star
发布于
2025-06-19
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时