Selenium 自动评分脚本 - 随机扣分优化
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time
import os
import random
def get_driver():
# 检查是否已经打开浏览器
browser_opened = False
for handle in webdriver.Chrome().window_handles:
browser_opened = True
break
# 创建浏览器实例或在已有浏览器中操作
if browser_opened:
options = Options()
options.debugger_address = '127.0.0.1:9222'
driver = webdriver.Chrome(options=options)
else:
os.system(r'start chrome --remote-debugging-port=9222 --user-data-dir="D:\评阅用"')
options = Options()
options.add_experimental_option('debuggerAddress', '127.0.0.1:9222')
driver = webdriver.Chrome(options=options)
return driver
driver = get_driver()
# 找到有'内蒙古开放大学'字样的标签页
while True:
for handle in driver.window_handles:
driver.switch_to.window(handle)
if '内蒙古开放大学' in driver.title:
print('登录成功')
break
else:
time.sleep(3)
continue
break
# 在网页内查找所有class属性为summary-sub-title的元素,并提取其中的数字
elements = driver.find_elements('class name', 'summary-sub-title')
for i, element in enumerate(elements):
text = element.text
num = ''.join(filter(str.isdigit, text))
num = int(num)
if random.randint(0, 1) == 1:
num = num - random.randint(1, 2) # 随机减去1-2
for j in range(random.randint(3, 4)): # 随机减3-4次
if num > 0:
num -= 1
print(f'第{i + 1}题分值为:{num}')
# 判断是否已经填写了答案
answer = driver.find_element('class name', 'answer-content')
if answer.text:
# 填写分数
print(f'第{i + 1}题答案已填写')
score_input = driver.find_elements('css selector', 'input[name='score']')[i]
score_input.send_keys(num)
time.sleep(1) # 等待自动保存
print(f'第{i + 1}题已打分:{num}')
功能说明:
- 使用 Selenium 库自动打开并操作 Chrome 浏览器,并登录内蒙古开放大学的网站。
- 查找所有包含“summary-sub-title” class 的元素,并提取其中的数字作为分数。
- 随机减分算法优化:
- 随机选择一半的数字,随机减去 1-2 分。
- 在所有数字中随机减去 3-4 次,确保分数不为负数。
- 使用 Selenium 的元素操作方法,将最终分数填入相应的输入框,完成自动评分。
使用方法:
- 将代码保存为 Python 文件,例如
auto_score.py。 - 确保已经安装 Selenium 库,可以使用
pip install selenium安装。 - 将代码中的
D:\评阅用修改为您的 Chrome 用户数据目录。 - 运行
auto_score.py文件,脚本将自动打开浏览器并完成评分。
注意:
- 该脚本仅供学习交流使用,请勿用于非法用途。
- 内蒙古开放大学的网站可能会更改,需要根据实际情况调整代码。
- 在使用该脚本之前,请仔细阅读并理解代码,并确保您已了解 Selenium 库的基本使用方法。
更多优化建议:
- 使用更加健壮的元素定位方法,例如 Xpath 或 CSS Selector,提高代码稳定性。
- 添加异常处理机制,防止代码因网站变化或意外情况而崩溃。
- 使用日志记录功能,记录脚本运行过程中的关键信息,方便排查问题。
- 添加多线程功能,提高脚本效率。
- 使用 Selenium Grid 运行测试,提高脚本的稳定性和可扩展性。
原文地址: http://www.cveoy.top/t/topic/fZi3 著作权归作者所有。请勿转载和采集!