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')
# 控制随机扣分的次数
random_deduction_count = random.randint(3, 4)
for i, element in enumerate(elements):
text = element.text
num = ''.join(filter(str.isdigit, text))
num = int(num)
# 随机减分
if random_deduction_count > 0:
num -= random.randint(1, 3)
random_deduction_count -= 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}')
功能改进:
- 随机扣分次数: 脚本现在会随机选择3-4次进行扣分操作,避免频繁扣分。
- 代码优化: 将随机减分逻辑移入循环内,使得代码更简洁,更易读。
- 说明: 本代码仅供参考,实际使用时需要根据具体情况进行调整。
原文地址: https://www.cveoy.top/t/topic/fZja 著作权归作者所有。请勿转载和采集!