Selenium 是一个用于 Web 应用程序测试的自动化测试工具,通过编写脚本(如Java、Python、Ruby 等),我们可以模拟用户在浏览器中的操作,例如点击、输入、页面跳转等。
这篇文章将介绍如何在springboot项目中使用selenium,浏览器选择 Chrome,主要步骤如下:
- 下载chrome driver
- SpringBoot项目引入依赖
- 写脚本
下载浏览器驱动
下载地址:chromedriver.chromium.org/downloads
driver版本要和浏览器相对应,请选择合适的版本
SpringBoot项目引入依赖
在 Gradle 的构建文件中添加 Selenium 的依赖项
dependencies {
// 其他依赖项...
implementation 'org.seleniumhq.selenium:selenium-java:4.0.0'
}
写脚本
编写 Java 代码来启动浏览器,进行网页导航、查找元素、执行操作等。以下是示例代码:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumExample {
public static void main(String[] args) {
// 设置 Chrome 浏览器的驱动程序路径
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// 创建 Chrome 浏览器实例
WebDriver driver = new ChromeDriver();
// 导航到网页
driver.get("<https://www.example.com/>");
// 查找元素并执行操作
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("selenium");
element.submit();
// 关闭浏览器
driver.quit();
}
}
请注意, "/path/to/chromedriver" 要替换为 Chrome 浏览器驱动程序的实际路径。
浏览器启动参数
我们可以在代码中设置浏览器启动参数
public WebDriver create() throws Exception {
// 设置浏览器参数
ChromeOptions options = getDefaultOptions();
// 设置驱动
System.setProperty("webdriver.chrome.driver", "xxx");
// 创建驱动对象
return options != null ? new ChromeDriver(options) : new ChromeDriver();
}
private ChromeOptions getDefaultOptions() {
ChromeOptions options = new ChromeOptions();
// 不打开图形浏览器
options.addArguments("--headless");
// 窗口大小
options.addArguments("--window-size=750,1424");
options.addArguments("--no-sandbox");
// 111 版本的chrome需要使用该参数 不然无法进行网络请求
options.addArguments("--remote-allow-origins=*");
return options;
}
其他常用参数
// 设置浏览器窗口大小
--window-size=1024,768
// 禁用 GPU 渲染加速
--disable-gpu
// 禁用扩展
--disable-extensions
// 禁用自动更新
--disable-background-networking --disable-default-apps --disable-extensions --disable-gpu --disable-sync --disable-translate --headless
// 禁用沙盒
--no-sandbox
// 设置用户代理
--user-agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36"
// 启动无头模式
--headless
其他常见操作及问题
判断页面是否加载完成
for (int i = 0; i < 1000; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
if (Objects.equals(js.executeScript("return document.readyState").toString(), "complete")) {
xxxxxx;
break;
}
}
截图
WebDriver driver = xxx; String b64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);