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

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

# 等待网页内所有'input[name='score']'元素出现并清空里面的内容
wait = WebDriverWait(driver, 10)
elements = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'input[name='score']')))
for element in elements:
    element.clear()

# 关闭浏览器
driver.quit()

代码功能:

  1. 使用 get_driver() 函数连接 Chrome 浏览器,并检查浏览器是否已经打开。
  2. 找到标题包含'内蒙古开放大学'的标签页,并确认登录成功。
  3. 使用 WebDriverWait 等待网页中所有 input[name='score'] 元素出现。
  4. 循环遍历所有找到的元素,并清空每个元素的内容。
  5. 最后关闭浏览器。

注意:

  • 需要确保已经安装了 Selenium 和 ChromeDriver。
  • 代码中使用的 'D:\评阅用' 是 Chrome 浏览器用户数据目录,需要根据实际情况修改。
  • 代码示例中使用了 'input[name='score']' 选择器来找到评分输入框,实际使用时可能需要根据网页结构调整选择器。
  • 代码示例中使用了 10 秒的等待时间,实际使用时可以根据页面加载速度进行调整。
Selenium 自动化测试:连接 Chrome 浏览器并清空评分输入框

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

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