1. linux(centos7)下载chrome以及chromeDriver
1.1 下载Chrome
下载chrome安装包
wget https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
安装依赖包
yum install -y lsb
yum install -y libXScrnSaver
yum install -y liberation-fonts
yum install -y libdbusmenu-gtk3
yum install epel-release
安装chrome
rpm ivh google-chrome-stable_current_x86_64.rpm
1.2 下载ChromeDriver
driver下载网址
https://chromedriver.storage.googleapis.com/index.html
选取chrome对应的chromedrvier版本
google-chrome -version 查看安装的chrome版本
1.3 将Springboot项目部署在LINUX上,以下是重要部分代码
@GetMapping("/screenShot")
public String screenShot() throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "/opt/driver/chromedriver");
ChromeOptions chromeOptions=new ChromeOptions();
//无头浏览器设置
chromeOptions.setHeadless(true);
//关闭chrome沙盒,不关闭会运行不了报错
chromeOptions.addArguments("--no-sandbox");
WebDriver webDriver = new ChromeDriver(chromeOptions);
try {
// 如果是linux或mac本地文件 需要在在路径前加file:
webDriver.get("file:/opt/HTML/1.html");
// webDriver.get("https://fanyi.baidu.com/");
Thread.sleep(5000);
File srcfile = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(srcfile, new File("/opt/screen/LZJ.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}finally {
webDriver.quit();
}
return "成功截屏";
}
访问项目地址,截图成功,以下是效果图
2.处理linux chrome中文乱码
可以看到中文部分乱码了,解决乱码问题的传送门
3.新的问题:截取整个网页的长图
3.1 推荐两个第三方框架
- ashot
- chrome-dp
3.2 ashot关键代码
<dependency>
<groupId>ru.yandex.qatools.ashot</groupId>
<artifactId>ashot</artifactId>
<version>1.5.4</version>
</dependency>
// 关键代码部分
......
WebDriver webDriver = new ChromeDriver(chromeOptions);
webDriver.get(url);
// 设置浏览器可视化窗口大小
webDriver.manage().window().setSize(new Dimension(1440, 1200));
Screenshot screenshot= new AShot().shootingStrategy(ShootingStrategies.viewportPasting( 2000 )).takeScreenshot(webDriver);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(screenshot.getImage(), "png", stream);
String encode = Base64.encode(stream.toByteArray());
.......