在Java项目中使用Selenium结合WebDriver可以实现对浏览器的自动化控制,无论是做Web功能的自动化测试,还是编写简单的网页爬虫,都能通过模拟真实用户的点击、输入、页面跳转等操作完成任务。这种方式相比直接请求接口更稳定,能应对大部分动态渲染的网页场景。

环境准备
首先需要在项目中引入Selenium的依赖,如果你使用Maven管理项目,在pom.xml中添加以下依赖即可:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.15.0</version>
</dependency>
然后需要下载对应浏览器的WebDriver驱动,比如使用Chrome浏览器就下载ChromeDriver,注意驱动版本要和本地安装的Chrome浏览器版本匹配,下载完成后把驱动文件放到项目的资源目录或者系统环境变量可访问的路径下。
初始化WebDriver
初始化WebDriver是使用Selenium的第一步,不同浏览器的初始化方式略有区别,以Chrome为例,代码如下:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
public class SeleniumDemo {
public static void main(String[] args) {
// 设置ChromeDriver的路径,如果已经加入环境变量可以省略这步
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
// 可选配置,关闭浏览器提示栏等
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-infobars");
// 初始化Chrome浏览器实例
WebDriver driver = new ChromeDriver(options);
// 访问目标网页
driver.get("https://ipipp.com");
// 后续操作...
}
}
模拟输入操作
模拟输入通常是对输入框元素进行操作,首先需要定位到目标输入框,Selenium提供了多种元素定位方式,常用的有通过id、name、class_name、xpath等定位。以下是一个在搜索框输入内容的示例:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class InputDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://ipipp.com/search");
// 通过id定位搜索输入框
WebElement searchInput = driver.findElement(By.id("search_input"));
// 清空输入框原有内容
searchInput.clear();
// 输入目标内容
searchInput.sendKeys("Selenium教程");
// 等待1秒查看效果
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit();
}
}
模拟点击操作
模拟点击可以操作按钮、链接等可点击元素,同样是先定位元素再调用点击方法,以下示例实现输入内容后点击搜索按钮的操作:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ClickDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://ipipp.com/search");
// 定位输入框并输入内容
WebElement searchInput = driver.findElement(By.id("search_input"));
searchInput.sendKeys("自动化测试");
// 定位搜索按钮并点击
WebElement searchBtn = driver.findElement(By.id("search_btn"));
searchBtn.click();
// 等待页面加载完成
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 打印当前页面标题
System.out.println("当前页面标题:" + driver.getTitle());
driver.quit();
}
}
常见问题说明
- 如果运行时提示找不到驱动,检查驱动路径是否正确,或者是否把驱动加入了系统环境变量。
- 元素定位失败时可以尝试用xpath定位,或者增加等待时间,避免页面还没加载完成就执行操作。
- 做爬虫使用时注意不要频繁请求目标网站,避免被反爬限制,可适当增加操作间隔。
- 使用完WebDriver后记得调用
driver.quit()方法关闭浏览器,释放资源。
进阶操作提示
除了基础的点击和输入,WebDriver还支持处理弹窗、切换窗口、执行JavaScript代码、获取元素属性等操作,可以根据实际需求扩展功能。如果是做自动化测试,还可以结合TestNG等测试框架实现用例管理和断言校验。