需要驱动真实浏览器验证老系统、跨浏览器兼容性或已有 Selenium 资产,并且团队更熟悉 Python/Java 生态。Selenium 只提供浏览器控制能力,测试框架、断言和报告要自己组合 pytest/JUnit;页面复杂时,等待策略和 Page Object 决定了用例是否稳定。
By.ID、By.CSS_SELECTOR、By.XPATH、By.NAME 等;优先 id 和稳定的 CSS,XPath 只用于无法用 CSS 表达的结构。WebDriverWait(driver, 10).until(EC.visibility_of_element_located(...)),针对具体条件轮询。driver.implicitly_wait(10) 对每次 find_element 生效,和显式等待混用会让超时难以推理,通常设为 0。driver 对应一个浏览器会话,用例结束必须 quit(),否则 CI 会残留进程和端口。安装 Selenium 与 pytest:
python -m venv .venv
source .venv/bin/activate
pip install selenium pytest
最小脚本(headless Chrome + 显式等待):
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
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
with webdriver.Chrome(options=options) as driver:
driver.get("http://127.0.0.1:3000/login")
driver.find_element(By.ID, "email").send_keys("qa@example.com")
driver.find_element(By.ID, "password").send_keys("test-password")
driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))
assert "工作台" in driver.find_element(By.TAG_NAME, "h1").text
Page Object 与 pytest 测试:
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
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def login(self, base_url, email, password):
self.driver.get(f"{base_url}/login")
self.driver.find_element(By.ID, "email").send_keys(email)
self.driver.find_element(By.ID, "password").send_keys(password)
self.driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
self.wait.until(EC.url_contains("/dashboard"))
h1 = (By.TAG_NAME, "h1")
return self.wait.until(EC.visibility_of_element_located(h1)).text
def test_login():
base_url = "http://127.0.0.1:3000"
options = webdriver.ChromeOptions()
options.add_argument("--headless=new")
with webdriver.Chrome(options=options) as driver:
page = LoginPage(driver)
assert page.login(base_url, "qa@example.com", "test-password") == "工作台"
启动 Selenium Grid:
# Selenium 4:Hub 与 Node 分开启动
java -jar selenium-server-4.27.0.jar hub
java -jar selenium-server-4.27.0.jar node --hub http://grid.example.com:4444
Python 侧通过 webdriver.Remote(command_executor="http://grid.example.com:4444", options=options) 接入 Grid,控制台地址是 http://grid.example.com:4444,可查看节点和会话队列。
CI 中执行 pytest 并保存报告:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: '3.12' }
- run: pip install -r requirements.txt
- run: pytest -q --junitxml=reports/junit.xml
- uses: actions/upload-artifact@v4
if: always()
with: { name: selenium-reports, path: reports/ }
runner 自带 Chrome 时,Selenium Manager 会自动准备驱动;要固定浏览器版本时,在 CI 里显式安装并锁定驱动,或改用 Grid 镜像统一环境。
time.sleep 等待:固定睡眠既拖慢通过用例,又在慢 CI 上偶发失败;改用针对 URL、可见性、可点击性的显式等待。WebElement 失效;不要跨操作缓存元素,重新查找或用 Page Object 方法每次定位。find_element 找不到就抛异常:需要判断存在性时用 find_elements 返回空列表,或 WebDriverWait 配合 presence_of_element_located。switch_to.frame(),结束后切回 default_content;新窗口要处理 window handles。close() 不调 quit():close() 只关当前窗口,driver 进程和 Grid 会话可能残留;fixture 的 teardown 里统一 quit()。time.sleep(3) 不可靠,应该怎样等待元素或页面状态?StaleElementReferenceException 的常见原因是什么,怎么修复?WebDriverWait 加 expected_conditions 等待 URL、可见性、可点击性等明确条件。
小程序版
微信扫码,随时查命令