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)
    for j in range(random.randint(3, 4)):
        if j < 2:
            num -= random.randint(1, 2)
    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(str(num))
        time.sleep(1)  # 等待自动保存
        print(f'第{i + 1}题已打分:{num}')
Python+Selenium自动化评分:内蒙古开放大学在线评阅系统实战

原文地址: https://www.cveoy.top/t/topic/fZi2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录