-
Python selenium 库
-
Selenium 是一个用于自动化 Web 浏览器操作的强大工具,广泛应用于 Web 应用程序测试、网页数据抓取和任务自动化等场景。
-
Selenium 为各种编程语言提供了 API,用作测试。 目前的官方 API 文档有 C#、JavaScript、Java、Python、Ruby。
-
Selenium 教程:https://www.runoob.com/selenium/
-
ChromeDriver 官网 https://sites.google.com/chromium.org/driver/home
-
下载地址 https://googlechromelabs.github.io/chrome-for-testing/#stable
-
注意是下载chromedriver 不是下载chrome
安装
pip3 install selenium安装成功查看
pip3 show seleniumChromeDriver 下载地址
https://googlechromelabs.github.io/chrome-for-testing/#stable
记得要和浏览器版本一直代码里面要配置这个安装路径
导入所需模块
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time设置正确的驱动路径
service = ChromeService(executable_path="/Users/你的目录/Desktop/work/chromedriver-mac-x64/chromedriver")
配置浏览器选项
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)打开一个网站
driver.get("https://www.baidu.com")
获取页面标题
print(driver.title)
查找搜索框元素
search_box = driver.find_element(By.ID, "chat-textarea")
在搜索框中输入 "测试"
search_box.send_keys("测试")
模拟按下回车键
search_box.send_keys(Keys.RETURN)
time.sleep(5)
关闭浏览器
driver.quit()
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ECChrome 配置
chrome_options = Options()
这时AI写的代码
service = Service("/Users/wjr/Desktop/work/chromedriver-mac-x64/chromedriver")
driver = webdriver.Chrome(service=service, options=chrome_options)try:
# 打开目标页面
url = "https://s.5aqima.com/login?redirect=https%3A%2F%2Fscratch.5aqima.com%2Fscratch%2Fv3"
driver.get(url)# 填入用户名和密码 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "//*[@id='normal_login_account']")) ).send_keys("12345567") driver.find_element(By.XPATH, "//*[@id='normal_login_password']").send_keys("42390655") # 点击登录按钮 login_button_xpath = "//*[@id='normal_login']/div[4]/div/div/div/div/div/button" WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, login_button_xpath)) ).click() # 等待目标元素加载完成 WebDriverWait(driver, 30).until( EC.presence_of_element_located((By.XPATH, "//*[@id='root']/div[1]/div/div[2]/div[1]/div[6]")) ) print("页面加载完成")finally:
# 可选:保持浏览器打开以便查看
input("按 Enter 键关闭浏览器...")
driver.quit()
selenium测试
小米渣的逆袭2026-04-16 18:59