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

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)
            browser.find_element(By.CLASS_NAME, 'nav-text').click()
        except:
            time.sleep(1)
            continue

脚本功能:

  1. 检查浏览器是否已打开,若未打开则启动浏览器。
  2. 切换到包含 '内蒙古开放大学' 的窗口,并打印登录成功信息。
  3. 找到 class 属性为 'score-box' 的元素,并获取其中的输入框。
  4. 清除输入框内容,并填写 94-99 之间的随机数。
  5. 模拟键盘输入回车键,提交分数。
  6. 点击 class 属性为 'nav-text' 的元素。
  7. 如果元素未找到,则继续等待。

使用说明:

  1. 将代码保存为 .py 文件。
  2. 安装 Selenium 库:pip install selenium
  3. 下载 ChromeDriver 并将其路径添加到系统环境变量。
  4. 修改代码中的 'D:\评阅用' 为您的 Chrome 用户数据目录。
  5. 运行脚本。

注意:

  • 该脚本仅供学习和参考,请勿用于任何违法行为。
  • 脚本可能需要根据网页结构进行调整。
  • 为了避免误操作,请谨慎使用。

代码解释:

  • check_browser() 函数用于检查浏览器是否已打开。
  • options 对象用于设置 Chrome 浏览器选项。
  • browser 对象表示 Chrome 浏览器实例。
  • window_handles 属性用于获取所有窗口句柄。
  • switch_to.window() 方法用于切换窗口。
  • find_element() 方法用于查找网页元素。
  • clear() 方法用于清除输入框内容。
  • send_keys() 方法用于模拟键盘输入。
  • click() 方法用于模拟鼠标点击。
  • time.sleep() 函数用于暂停执行。

希望以上信息对您有所帮助。如果您还有其他问题,请随时提出。

Python Selenium 脚本自动填写网页分数并提交

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

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