python的selenium库模拟输入和点击

使用python打开已经登录的谷歌浏览器,模拟录入文本提交数据。

1、执行命令行,系统会打开浏览器,手工登录
"C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9223 --user-data-dir="C:\tmp"
2、下载谷歌驱动,先看谷歌版本,再谷歌地址栏输入:chrome://settings/help

获取版本号:版本 133.0.6943.60(正式版本) (64 位),再根据版本号下载谷歌驱动chromedriver.exe。我百度了好几次,才找到一个 ChromeDriver 132.0.6834.110。chrome133的可以用。

3、pythton代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9223")  # 默认调试端口为9222
# 指定 ChromeDriver 的路径
driver_path = r"C:\tmp\chromedriver.exe"

# 创建 Service 对象并指定 ChromeDriver 路径
service = Service(executable_path=driver_path)
# 创建 WebDriver 实例,连接到已打开的 Chrome 浏览器
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
    # 等待页面加载完成
    driver.implicitly_wait(5)
    # 假设文本框和提交按钮的 XPath 路径如下
    text_box_xpath = '/html/body/div/div/div[2]/div[1]/div/div[2]/div[3]/div[1]/div/div[1]/div/div/textarea'  # 替换为实际的 XPath
    submit_button_xpath = '/html/body/div/div/div[2]/div[1]/div/div[2]/div[3]/div[1]/div/div[3]/img'  # 替换为实际的 XPath
    print(f"大循环开始,共500次")
    # 大循环,运行10次
    for i in range(500):
        print(f"开始第 {i + 1} 次操作...")
        # 等待文本框变为可交互状态
        text_box = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, text_box_xpath))
        )
        text_box.clear()  # 清空文本框内容
        text_box.send_keys("请写个排比句 ",i+1)
        # 等待1秒
        time.sleep(1)
        # 等待提交按钮变为可点击状态
        submit_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, submit_button_xpath))
        )
        submit_button.click()
        # 等待直到文本框重新出现或超时
        while True:
            try:
                # 使用 WebDriverWait 等待文本框出现且可交互,超时时间为10秒
                WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, text_box_xpath))
                )
                print("文本框已找到且可交互,进入下一次循环")
                break  # 如果找到文本框,跳出等待循环
            except Exception as e:
                # 如果没有找到文本框,打印日志并继续等待
                print("未找到文本框或不可交互,继续等待...")
                continue
        print(f"第 {i + 1} 次操作完成!")

except Exception as e:
    print(f"发生错误: {e}")
finally:
    # 不关闭浏览器,保持会话
    pass

你可能感兴趣的:(selenium,测试工具)