Selenium 的学习

Selenium 是一款流行的自动化测试工具,支持多种编程语言。
但是没想到项目上会用 Java 来写 Selenium 脚本,网上普遍都是 Python 的写的。
很奇怪但是 business is business,还是要学会的。

1. 环境准备

  • 安装 JDK(推荐 8 及以上)
  • 下载并引入 Selenium Java 依赖(Maven 示例):
1
2
3
4
5
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.19.1</version>
</dependency>
  • 下载对应浏览器的 WebDriver(如 ChromeDriver)并配置到系统 PATH。

2. 启动浏览器

1
2
3
4
5
6
7
8
9
10
11
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumDemo {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.baidu.com");
System.out.println(driver.getTitle());
driver.quit();
}
}

3. 查找元素

1
2
3
4
5
6
7
8
9
10
11
12
// By id
WebElement input = driver.findElement(By.id("kw"));
// By name
WebElement btn = driver.findElement(By.name("btnK"));
// By className
WebElement logo = driver.findElement(By.className("logo"));
// By tagName
WebElement form = driver.findElement(By.tagName("form"));
// By cssSelector
WebElement link = driver.findElement(By.cssSelector("a[href='https://news.baidu.com']"));
// By xpath
WebElement nav = driver.findElement(By.xpath("//div[@id='u1']"));

4. 元素操作

1
2
3
4
5
6
7
8
9
10
// 输入内容
input.sendKeys("Selenium");
// 点击按钮
btn.click();
// 获取文本
String text = logo.getText();
// 清空输入框
input.clear();
// 判断元素是否显示
boolean visible = btn.isDisplayed();

5. 等待元素出现

1
2
3
4
5
6
7
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement result = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("content_left"))
);

6. 处理下拉框

1
2
3
4
5
6
import org.openqa.selenium.support.ui.Select;

Select select = new Select(driver.findElement(By.id("dropdownId")));
select.selectByVisibleText("选项1");
select.selectByValue("value1");
select.selectByIndex(2);

7. 处理弹窗(Alert)

1
2
3
4
Alert alert = driver.switchTo().alert();
alert.accept(); // 确认
alert.dismiss(); // 取消
String msg = alert.getText();

8. 处理多窗口/标签页

1
2
3
4
5
6
String mainWindow = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(mainWindow)) {
driver.switchTo().window(handle);
}
}

9. 执行 JS 脚本

1
2
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

10. 截图

1
2
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
Files.copy(screenshot.toPath(), Paths.get("screenshot.png"));

11. 关闭浏览器

1
2
driver.quit(); // 关闭所有窗口
// 或 driver.close(); // 关闭当前窗口

自动化确实是一个很有趣的领域,我想以后的工作能不能都自动化,然后我就可以躺平了。