Selenium Web自动化工具

一、引入依赖

Chrome浏览器驱动官方下载地址:http://chromedriver.storage.googleapis.com/index.html

1
2
3
4
5
6
7
8
9
10
11
12
<!--selenium库下载地址:http://selenium-release.storage.googleapis.com/index.html-->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.4</version>
</dependency>
<!--解决'tried to access method com.google.common.util.concurrent.SimpleTimeLimiter'错误-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>

二、参考例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
String DRIVER_PATH = "classpath:/chromedriver.exe";
//文件放resource目录下
Sting DRIVER_PATH=“classpath:/chromedriver.exe”
ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource resource = resourceLoader.getResource(DRIVER_PATH);
System.setProperty("webdriver.chrome.driver",resource.getURL().getPath());

ChromeOptions chromeOptions = new ChromeOptions();

chromeOptions.addArguments("disable-infobars");//关闭Chrome正在受到自动软件的控制
chromeOptions.addArguments("--disable-web-security");//允许重定向
chromeOptions.addArguments("headless"); //浏览器后台运行
chromeOptions.addArguments("sec-fetch-site=same-site");
chromeOptions.addArguments("--disable-blink-features");
chromeOptions.addArguments("--disable-blink-features=AutomationControlled");//发现主要是这句是关键

//开启一个实验性参数excludeSwitches,用来隐藏window.navigator.webdriver返回true,这个参数必须是List
chromeOptions.setExperimentalOption("excludeSwitches", Lists.newArrayList("enable-automation"));

// 1.创建webdriver驱动
WebDriver driver = new ChromeDriver(chromeOptions);

//解决对window.navigator.webdriver的检测机制
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});");


// 2.打开小说登陆
driver.get(LOGIN_URL);
//Thread.sleep(5000);
////定位input输入账号密码
driver.findElement(By.id("Username")).sendKeys("295170898@qq.com");
Thread.sleep(3000);
driver.findElement(By.id("Password")).sendKeys("0nuB!IQWdnJ8");
Thread.sleep(3000);
driver.findElement(By.name("button")).click();
Thread.sleep(3000);
// 3.获取输入框,输入selenium
driver.findElement(By.id("kw")).sendKeys("selenium");
// 4.获取“百度一下”按钮,进行搜索
driver.findElement(By.id("su")).click();
// 5.退出浏览器
driver.quit();