1.版本
selenium
<!--selenium-->
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.0.3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.141.59</version>
</dependency>
geckodriver版本:0.29.1
安装详见:selenium java安装运行_leadseczgw01的博客-CSDN博客
2.实现百度搜索
public String baiduSearch(String profileName, String searchKeyword) throws Exception{
WebDriver driver = getWebDriver(profileName);
// 打开网址
driver.get("https://www.baidu.com/");
Thread.sleep(1000 * 3);
SeleniumFirefoxUtil.detectAndCloseLoginTip(driver); // 探测并关闭登录提示
// 找到搜索文本框
WebElement webElement = driver.findElement(By.id("kw"));
webElement.sendKeys(searchKeyword);
// 找到搜索点击按钮,并点击
webElement = driver.findElement(By.id("su"));
webElement.click();
Thread.sleep(1000 * 3);
webElement = driver.findElement(By.xpath("//div[@id='tsn_inner']/div[2]/span"));
String btnText = webElement.getText();
logger.debug("搜索结果:{}!", btnText);
// 退出浏览器
driver.quit();
return btnText;
}
private WebDriver getWebDriver(String profileName) {
try{
// 指定火狐浏览器安装位置
System.setProperty("webdriver.firefox.bin", firefoxBin);
// 指定selenium 火狐浏览器驱动程序位置
System.setProperty("webdriver.gecko.driver", driverPath);
// 获取火狐浏览器驱动对象
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
firefoxOptions.addArguments("--no-sandbox");
firefoxOptions.addArguments("--disable-gpu");
firefoxOptions.addArguments("--disable-dev-shm-usage");
if(StringUtils.isNotBlank(profileName)){
String profilePath = firefoxProfileHome + File.separator + profileName;
logger.debug("profilePath:{}", profilePath);
File profileFile = new File(profilePath);
if(!profileFile.exists()){
logger.error("profilePath:{}不存在或权限不足!", profilePath);
}else{
FirefoxProfile profile = new FirefoxProfile(profileFile);
firefoxOptions.setProfile(profile);
}
}
FirefoxDriver firefoxDriver = new FirefoxDriver(firefoxOptions);
firefoxDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
firefoxDriver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
return firefoxDriver;
}catch (Exception e){
logger.error("获取webDriver异常!", e);
}
return null;
}