Selenium 指南
安装与初始化 — Java & Python
// Java
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new", "--no-sandbox");
WebDriver driver = new ChromeDriver(options);
driver.get("https://example.com");
driver.quit();
---
# Python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
driver.get("https://example.com")
print(driver.title)
driver.quit()
定位器
// Java
driver.findElement(By.id("email"));
driver.findElement(By.cssSelector("input[type='email']"));
driver.findElement(By.xpath("//button[@type='submit']"));
driver.findElements(By.className("list-item"));
---
# Python
from selenium.webdriver.common.by import By
driver.find_element(By.ID, "email")
driver.find_element(By.CSS_SELECTOR, "input[type='email']")
driver.find_elements(By.CLASS_NAME, "list-item")
显式等待
// Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement el = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("result"))
);
wait.until(ExpectedConditions.urlContains("/dashboard"));
---
# Python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
el = wait.until(EC.visibility_of_element_located((By.ID, "result")))
页面对象模型
// Java — LoginPage.java
public class LoginPage {
@FindBy(id = "email") private WebElement emailField;
@FindBy(id = "password") private WebElement passwordField;
@FindBy(css = "button[type='submit']") private WebElement submitButton;
public LoginPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public DashboardPage login(String email, String password) {
emailField.sendKeys(email);
passwordField.sendKeys(password);
submitButton.click();
return new DashboardPage(driver);
}
}
表单操作与键盘
// Java
import org.openqa.selenium.support.ui.Select;
Select select = new Select(driver.findElement(By.id("country")));
select.selectByVisibleText("中国");
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).perform();
---
# Python
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element(By.ID, "country"))
select.select_by_visible_text("中国")
Grid 配置
# 启动 Hub
java -jar selenium-server-4.x.jar hub
# 启动 Node
java -jar selenium-server-4.x.jar node \
--hub http://localhost:4444
// Java — 连接 Grid
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444"),
new ChromeOptions()
);