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 "成功截屏";
}
访问项目地址,截图成功,以下是效果图