调用谷歌的无界浏览器,最起码得先装一个谷歌浏览器,然后进行下一步,
添加pom依赖,或者单独导入jar包也可以
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-1</version>
</dependency>
selenium的版本选高一点,我用3.x的版本报错了。
或者直接用这个链接下载,版本自己选
http://selenium-release.storage.googleapis.com/index.html
然后下载谷歌浏览器的无界驱动
http://chromedriver.storage.googleapis.com/index.html
版本根据自己电脑上的谷歌浏览器匹配就好,有可能你装的64位的,但驱动只有32位的,这没关系,我自己是64位的浏览器,用32位的驱动照样可以
下来就是代码:
#生成的图片存储位置
img.path = E:\\js\\phantomjs-2.1.1-windows\\bin\\report\\img\\
#调用的Chrome浏览器驱动存放位置
chromedriver.path = E:\\js\\phantomjs-2.1.1-windows\\bin\\chromedriver.exe
#调用的Chrome浏览器安装位置
chrome.path = C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe
最好把这些地址都做成配置文件,我用的是springboot,就直接放在properties文件里了。
public void createChart(C3Info c3Entiy)
{
String url = getUrl(c3Entiy);
log.info("[准备发送远程请求:{}]",url);
String imgSavePath1 = reportPath + c3Entiy.getPrePriId() + "_chart12.png";
String imgSavePath2 = reportPath + c3Entiy.getPrePriId() + "_chart34.png";
try{
//设置驱动地址
System.setProperty("webdriver.chrome.driver",driverPath);
ChromeOptions options = new ChromeOptions();
//设置谷歌浏览器exe文件所在地址
options.setBinary(chromePath);
//这里是要执行的命令,如需修改截图页面的尺寸,修改--window-size的参数即可"--window-size=1920,1200",
options.addArguments("--headless","--window-size=1920,1200","--disable-gpu","--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
// 访问页面
driver.get(url);
// 页面等待渲染时长,单位默认是秒
Wait<WebDriver> wait = new WebDriverWait(driver, 10);
wait.until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver web) {
//若无需等待渲染,return true即可。
return web.findElement(By.id("chart12"));
//chart12就是需要截图的div的id
}
});
Thread.sleep(6000); //等待页面完全加载
WebElement element = driver.findElement(By.id("chart12"));
File chart12File = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(chart12File, new File(imgSavePath1));
//可以多次截图,指向不同的div就可以
element = driver.findElement(By.id("chart34"));
File chart34File = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(chart34File, new File(imgSavePath2));
driver.quit();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("[生成的图片完成]");
}
效果图:
自己原创,有不当之处,欢迎下方留言指正交流