1、selenium环境配置,确保本机安装的chrome与chromedriver版本一致。
chromedriver下载路径: chromedriver.chromium.org/downloads
chrome版本查看:
打开chrome浏览器,点击“帮助”--“关于google chrome”,查看版本号:如 “版本 111.0.5563.147(正式版本) (64 位)” 对应的chromedriver版本为 “ChromeDriver 111.0.5563.64”
2、新建java--maven项目、引入以下jar包
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.7.1</version>
</dependency>
3、编写java自动化测试代码
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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class SeleniumTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","D:/chromedriver.exe");
System.setProperty("webdriver.chrome.whitelistedIps", "");
ChromeOptions option = new ChromeOptions();
option.addArguments("--remote-allow-origins=*");
// 创建一个新的Chrome浏览器实例
WebDriver driver = new ChromeDriver(option);
// 打开一个网页
driver.get("https://www.baidu.com");
// 查找一个搜索框
WebElement searchBox = driver.findElement(By.id("kw"));
// 在搜索框中输入关键字
searchBox.sendKeys("我不做大哥很多年");
// 点击搜索按钮
searchBox.submit();
// 等待搜索结果页面加载完成
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
//抓取推荐框内容
WebElement content_right=wait.until(ExpectedConditions.elementToBeClickable(By.id("content_right")));
// 输出搜索结果数量
System.out.println("=============================================");
System.out.println("搜索结果数量:" + content_right.getText());
// 关闭浏览器
driver.quit();
}
}