超星学习通/中科大实验室安全考试自动答题脚本保姆级教程(Python版,含Cookie获取)

张开发
2026/4/19 21:10:28 15 分钟阅读

分享文章

超星学习通/中科大实验室安全考试自动答题脚本保姆级教程(Python版,含Cookie获取)
超星学习通实验室安全考试自动化解决方案实战指南实验室安全考试是高校学生必须面对的常规考核之一但反复刷题的过程往往耗时费力。作为一名长期研究教育自动化工具的技术爱好者我发现通过Python脚本与浏览器开发者工具的结合可以高效解决这个问题。本文将分享一套经过实战检验的完整方案从网络请求分析到脚本调试带你深入理解自动化答题的实现原理。1. 准备工作与环境配置在开始编写自动化脚本前我们需要做好充分的准备工作。不同于简单的代码复制粘贴理解整个技术栈的运行机制至关重要。首先确保你的开发环境满足以下要求Python 3.8或更高版本Chrome浏览器用于网络请求分析代码编辑器VS Code或PyCharm等基本的Python编程知识安装必要的Python库pip install requests pyquery selenium提示建议使用虚拟环境管理项目依赖避免与其他项目产生冲突。可以通过python -m venv venv创建虚拟环境。浏览器开发者工具是本次项目的关键工具。在Chrome中按下F12或右键选择检查即可打开。我们需要特别关注Network网络选项卡这里记录了所有HTTP请求和响应。2. 网络请求分析与接口破解理解超星学习通的API调用方式是实现自动化的核心。通过系统分析我发现其考试系统主要依赖以下几个关键接口试题获取接口 - 用于加载考试题目答案提交接口 - 用于提交用户选择结果查询接口 - 用于验证答题结果2.1 捕获关键API请求按照以下步骤捕获网络请求登录超星学习通平台进入实验室安全考试页面开始考试前打开开发者工具切换到Network选项卡并勾选Preserve log开始考试后观察新增的网络请求重点关注以下请求特征URL包含quiz或exam关键字请求方法为POST或GET响应内容为JSON格式典型请求示例GET /app/quiz/test/start?examId12345 HTTP/1.1 Host: appswh.chaoxing.com Cookie: [你的登录Cookie]2.2 Cookie获取与维护身份验证是自动化过程中的关键环节。超星学习通使用Cookie维持会话状态我们需要获取有效的登录凭证。手动获取Cookie的方法登录后按F12打开开发者工具进入Application选项卡在左侧选择Cookies查找名为uc01或类似的关键Cookie复制完整的Cookie字符串注意Cookie具有时效性通常几小时后会失效。长期运行的脚本需要实现自动刷新机制。3. Python自动化脚本开发基于前面的分析我们可以构建一个完整的自动化答题系统。下面分模块讲解核心代码实现。3.1 试题获取模块import requests import json def fetch_questions(exam_id, cookie): headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64), Cookie: cookie } params { examId: exam_id, pageSize: 100 # 一次性获取所有题目 } response requests.get( https://appswh.chaoxing.com/app/quiz/test/getQuestions, headersheaders, paramsparams ) if response.status_code 200: return response.json() else: raise Exception(f获取试题失败: {response.status_code})3.2 答案分析与处理试题返回的JSON数据结构通常包含以下关键字段questionId: 题目唯一标识questionTitle: 题目内容answerList: 选项列表rightAnswer: 正确答案标识答案处理函数示例def parse_answers(questions): answer_map {} for q in questions[data][questionArray]: question_id q[id] correct_answers q[rightAnswer] options q[answerList] # 处理多选题情况 if len(correct_answers) 1: answer_text 、.join([options[ord(a.lower())-97] for a in correct_answers]) else: answer_text options[ord(correct_answers.lower())-97] answer_map[question_id] { correct: correct_answers, text: answer_text } return answer_map3.3 自动答题实现def submit_answers(exam_id, answers, cookie): headers { User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64), Cookie: cookie, Content-Type: application/json } results [] for qid, answer in answers.items(): data { examId: exam_id, questionId: qid, answer: answer[correct] } response requests.post( https://appswh.chaoxing.com/app/quiz/test/submitAnswer, headersheaders, jsondata ) results.append({ question: qid, status: response.status_code, response: response.json() }) return results4. 异常处理与调试技巧在实际运行中脚本可能会遇到各种意外情况。以下是几个常见问题及解决方案4.1 Cookie失效处理实现Cookie自动刷新的策略检测到401未授权状态码时触发刷新使用Selenium模拟登录获取新Cookie更新内存中的Cookie并重试请求from selenium import webdriver def refresh_cookie(username, password): driver webdriver.Chrome() driver.get(https://passport2.chaoxing.com/login) # 填写登录表单 driver.find_element(id, username).send_keys(username) driver.find_element(id, password).send_keys(password) driver.find_element(id, loginBtn).click() # 等待登录完成 time.sleep(5) # 获取新Cookie cookies driver.get_cookies() new_cookie ; .join([f{c[name]}{c[value]} for c in cookies]) driver.quit() return new_cookie4.2 接口变更应对教育平台经常会更新API接口建议采取以下防御性编程策略将API端点配置为变量便于统一修改实现请求重试机制添加详细的日志记录import logging logging.basicConfig( levellogging.INFO, format%(asctime)s - %(levelname)s - %(message)s ) API_ENDPOINTS { get_questions: /app/quiz/test/getQuestions, submit_answer: /app/quiz/test/submitAnswer } def make_request(url, methodGET, retries3, **kwargs): for attempt in range(retries): try: response requests.request(method, url, **kwargs) if response.status_code 200: return response else: logging.warning(f请求失败: {response.status_code}) except Exception as e: logging.error(f请求异常: {str(e)}) if attempt retries - 1: time.sleep(2 ** attempt) # 指数退避 raise Exception(f请求失败重试{retries}次后仍不成功)5. 系统优化与扩展基础功能实现后我们可以进一步优化系统的可靠性和用户体验。5.1 性能优化策略使用会话保持减少连接开销session requests.Session() session.headers.update({User-Agent: Mozilla/5.0})实现异步请求提高吞吐量import aiohttp import asyncio async def async_submit_answer(session, url, data): async with session.post(url, jsondata) as response: return await response.json() async def batch_submit(answers): async with aiohttp.ClientSession() as session: tasks [] for answer in answers: task async_submit_answer(session, API_ENDPOINTS[submit], answer) tasks.append(task) return await asyncio.gather(*tasks)5.2 功能扩展思路添加GUI界面提升易用性实现错题本功能记录错误题目开发题库更新机制保持答案准确添加多账号支持批量处理# 简单的Tkinter界面示例 import tkinter as tk from tkinter import messagebox class ExamAutoApp: def __init__(self): self.window tk.Tk() self.setup_ui() def setup_ui(self): self.window.title(实验室安全考试助手) tk.Label(self.window, text考试ID:).grid(row0) self.exam_id_entry tk.Entry(self.window) self.exam_id_entry.grid(row0, column1) tk.Button(self.window, text开始答题, commandself.start_exam).grid(row1) def start_exam(self): exam_id self.exam_id_entry.get() try: result run_auto_exam(exam_id) messagebox.showinfo(成功, f已完成答题得分: {result[score]}) except Exception as e: messagebox.showerror(错误, str(e)) def run(self): self.window.mainloop()在实际项目中这套系统帮助我和身边同学节省了大量重复刷题时间。最关键的体会是理解原理比复制代码更重要只有深入分析平台运行机制才能写出稳定可靠的自动化脚本。当遇到接口变更时重新分析网络请求往往比盲目修改代码更有效。

更多文章