chrome浏览器webDriver驱动下载,注意要与电脑上实际安装的浏览器版本相对应
原理说明:
java代码直接通过selenium-java库中的核心类ChromeDriver调用本地下载的webDriver驱动,webDriver驱动会自动找到其对应操作系统安装的浏览器模仿人类执行相关的操作
POM依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
selenium-java依赖版本过高会导致下方异常
Exception in thread "main" java.lang.NoClassDefFoundError: org/openqa/selenium/internal/Require
....
Caused by: java.lang.ClassNotFoundException: org.openqa.selenium.internal.Require
参考:https://blog.csdn.net/m0_56758840/article/details/123380448
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.awt.image.BufferedImage;
/**
* @author JHL
* @version 1.0
* @date 2022/8/25 14:50
* @since : JDK 11
*/
public class T {
public static void main(String[] args) throws InterruptedException {
// 设置jvm系统属性,selenium会读取这个数据找到要使用的webDriver驱动
System.setProperty("webdriver.chrome.driver",
"D:/env/chromedriver_win32/chromedriver.exe");
// 设置驱动的选项
ChromeOptions options = new ChromeOptions();
// 设置无头浏览器,即不打开窗口渲染,都在内存中执行
options.setHeadless(true);
// 根据选项实例化驱动
ChromeDriver driver = new ChromeDriver(options);
// 访问百度,并搜索hello world
driver.get("http://www.baidu.com");
driver.findElement(By.name("wd")).sendKeys("hello word!");
driver.findElement(By.id("su")).click();
Thread.sleep(5000);
// 搜索结果页面的html源码
System.out.println(driver.getPageSource());
// 截图方式一
// File file = driver.getScreenshotAs(OutputType.FILE);
// 截图方式二
BufferedImage screenshot = driver.getScreenshotAs(new OutputType<>() {
@Override
public BufferedImage convertFromBase64Png(String base64) {
return ImgUtil.toImage(base64);
}
@Override
public BufferedImage convertFromPngBytes(byte[] bytes) {
return ImgUtil.toImage(bytes);
}
});
ImgUtil.write(screenshot, FileUtil.newFile("截图.png"));
driver.quit();
}
使用参考:
https://blog.csdn.net/chenjxj123/article/details/121802904
https://www.cnblogs.com/ychun/p/14282422.html
标签:java,selenium,driver,org,import,浏览器,操作 From: https://www.cnblogs.com/hhddd-1024/p/16624972.html