import os
import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def check_browser():
    '''检查是否已经打开了浏览器'''
    try:
        options = Options()
        options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
        browser = webdriver.Chrome(options=options)
        browser.execute_script('return true')
        return True
    except:
        return False

if __name__ == '__main__':
    if not check_browser():
        os.system(r'start chrome --remote-debugging-port=9527 --user-data-dir='D:\评阅用'')

    options = Options()
    options.add_experimental_option('debuggerAddress', '127.0.0.1:9527')
    browser = webdriver.Chrome(options=options)

    while True:
        for handle in browser.window_handles:
            browser.switch_to.window(handle)
            if '内蒙古开放大学' in browser.title:
                print('用户登录成功!')
                break
        else:
            time.sleep(1)
            continue
        break

    while True:
        try:
            # 找到分数输入框并输入随机分数
            score_box = browser.find_element(By.CLASS_NAME, 'score-box')
            score_input = score_box.find_element(By.TAG_NAME, 'input')
            score_input.clear()
            score_input.send_keys(str(random.randint(94, 99)))
            score_input.send_keys(Keys.ENTER)
            time.sleep(1)
            
            # 等待提示信息消失
            WebDriverWait(browser, 10).until(EC.invisibility_of_element_located((By.CLASS_NAME, 'toast-message')))
            
            # 点击指定按钮
            browser.find_element(By.CLASS_NAME, 'nav-text').click()
        except:
            time.sleep(1)
            continue

代码功能:

  1. 检查浏览器: 检查是否已打开 Chrome 浏览器并开启远程调试端口。
  2. 连接浏览器: 连接到已打开的浏览器。
  3. 查找目标页面: 查找包含特定标题的页面。
  4. 循环输入分数:
    • 查找 class 属性为 'score-box' 的元素,并找到其内部的输入框。
    • 清空输入框内容,并输入 94-99 之间的随机整数。
    • 模拟键盘输入回车键。
    • 等待 class 属性为 'toast-message' 的元素消失,确保操作完成。
    • 点击 class 属性为 'nav-text' 的按钮。
  5. 异常处理: 如果出现异常,则等待 1 秒后继续循环。

使用说明:

  1. 请确保已安装 Python 和 Selenium 库。
  2. 请将代码中的 '内蒙古开放大学' 替换为实际的页面标题。
  3. 请根据实际情况修改元素选择器和等待时间。
  4. 运行代码前,请先打开 Chrome 浏览器,并开启远程调试端口 (端口号为 9527)。
Python Selenium 自动化评分:循环输入随机分数并点击按钮

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

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