import os
import time
import random
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

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)

    # 查找关键字为内蒙古开放大学的标签页
    for handle in browser.window_handles:
        browser.switch_to.window(handle)
        if '内蒙古开放大学' in browser.title:
            break

    # 在该页面上找到名称为score的name元素
    element = browser.find_element(By.NAME, 'score')
    # 清除输入框内容
    element.clear()
    # 生成95到99的随机数
    score = random.randint(95, 99)
    # 输入随机生成的成绩
    element.send_keys(str(score))
    print(f'输入成绩为: {score}')
Python Selenium 自动化控制浏览器:查找标签页并输入随机成绩

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

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