Java如何安装前提:Selenium⾃动化
java版本最低要求为8
电脑⾄少已安装⼀种浏览器,如:Chrome(推荐)、Edge、Firefox、IE、Safari
提⽰:浏览器必须为官⽹下载的正版浏览器,根据以往经验,存在部分同学电脑安装的浏览器为盗
版,导致⽆法执⾏⾃动化
1.打开intellij idea,创建Maven项⽬
![![[Pasted image 20260731153420.png]]](https://www.wsisp.com/helps/wp-content/uploads/2026/07/20260731093236-6a6c6bb4bad4f.png)
2. 添加依赖
![![[Pasted image 20260731153604.png]]](https://www.wsisp.com/helps/wp-content/uploads/2026/07/20260731093237-6a6c6bb53425c.png)
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.8.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.29.0</version>
</dependency>
3.在test路径下创建自动化文件
3.1项目结构
![![[Pasted image 20260731153848.png]]](https://www.wsisp.com/helps/wp-content/uploads/2026/07/20260731093237-6a6c6bb58b3bd.png)
3.2代码
firstTest.java
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
import java.util.List;
public class firstTest {
void searchTest() throws InterruptedException {
// 驱动程序管理的自动化
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
//这个是我的谷歌浏览器的路径
options.setBinary("E:\\\\Chrome\\\\Application\\\\chrome.exe");
// 允许访问所有链接
options.addArguments("–remote-allow-origins=*");
//1.打开浏览器
WebDriver driver = new ChromeDriver(options);
//2.输入百度链接
driver.get("https://www.baidu.com");
//****************** xpath 定位 *******
/*3、找到输入框并输入
driver.findElement (By.xpath("//*[@id=\\"chat-textarea\\"]")).sendKeys ("csdn");
Thread.sleep(3000);
//4、找到“百度一下”按钮并点击
driver.findElement(By.xpath("//*[@id=\\"chat-submit-button\\"]")).click();*/ //*************************************************************************
//****************** cssSelector 定位***********************
//3、找到输入框并输入
//driver.findElement (By.cssSelector("#chat-textarea")).sendKeys ("csdn");
//Thread.sleep(3000);
//4、找到“百度一下”按钮并点击
//driver.findElement(By.cssSelector("#chat-submit-button")).click();
//*************************************************************************
//5、关闭浏览器
driver.quit();
}
}
xpath 定位 和 cssSelector 定位选择一个即可,方法不一样,结果是一样的
runTest.java
public class runTest {
public static void main(String[] args) throws InterruptedException {
firstTest test = new firstTest();
test.searchTest();
}
}
4.运⾏⾃动化
点击运⾏,程序将⾃动实现百度搜索全过程。
![![[Pasted image 20260731155007.png]]](https://www.wsisp.com/helps/wp-content/uploads/2026/07/20260731093237-6a6c6bb5a8b46.png)
5. 具体细节请看下集
https://blog.csdn.net/2302_77623737/article/details/163372094?spm=1001.2014.3001.5502
网硕互联帮助中心

评论前必须登录!
注册