zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Java利用ChromeDriver插件网页截图(Wondows版+Linux版)

2023-04-18 15:22:43 时间

chromedriver是谷歌浏览器驱动,用来模拟谷歌运行操作的一个工具,本文主要讲解Java后端利用此插件进行网页截图,并且适配Linux部署。

环境准备

Wondows服务器或电脑

本机需安装Chrome谷歌浏览器,根据本机浏览器版本,下载对应的chromedriver版本,chromedrive插件下载地址:https://registry.npmmirror.com/binary.html?path=chromedriver/,下载后解压即可。PS:网上看到许多需要配置环境变量的,实测根本不需要。
注意:插件版本和本机浏览器版本一定要对应

Linux服务器

安装Chrome

yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

查看版本

google-chrome --version

根据版本下载插件,chromedrive插件下载地址:https://registry.npmmirror.com/binary.html?path=chromedriver/,选择Linux版,上传到服务器后解压,上面默认安装最新版本。

// 解压
unzip chromedriver_linux64.zip 
// 赋权
chmod 777 chromedriver
// 安装浏览器中文字体
yum -y groupinstall Fonts

Java代码部分

引入maven

 <!-- 浏览器截图jar包 -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>27.0-jre</version>
        </dependency>

截图工具方法类

代码里面用到的是ChromeDriverService启动,还有一种是:
ChromeDriver driver = new ChromeDriver(options);
System.setProperty("webdriver.chrome.driver", "/data/server/legal-document-library-task/chromedriver");
这种在高并发,频繁截图时会遇到ChromeDriver插件未正常关闭的情况,会占用端口或内存。推荐使用ChromeDriverService方式。

public String imgUntil(String url){
        ChromeDriver driver = null;
        FileInputStream inputFile = null;
        ChromeDriverService service = null;
        try {
            //(推荐),利用ChromeDriverService启动
            //这里"/data/server/legal/chromedriver"是下载的驱动路径,Windows对应chromedriver.exe Linux对应chromedriver,具体路径看你把驱动放在哪
            service = new ChromeDriverService.Builder().usingDriverExecutable(new File("/data/server/legal/chromedriver")).usingAnyFreePort().build();
            service.start();
            ChromeOptions options = new ChromeOptions();
            //ssl证书支持
            options.setCapability("acceptSslCerts", true);
            //截屏支持
            options.setCapability("takesScreenshot", true);
            //css搜索支持
            options.setCapability("cssSelectorsEnabled", true);
            //设置浏览器参数
            options.addArguments("--headless");
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-gpu");
            options.addArguments("--disable-dev-shm-usage");
            options.setHeadless(true);
            driver = new ChromeDriver(service,options);
            //设置超时,避免有些内容加载过慢导致截不到图
            driver.manage().timeouts().pageLoadTimeout(1, TimeUnit.MINUTES);
            driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES);
            driver.manage().timeouts().setScriptTimeout(1, TimeUnit.MINUTES);
            //设置需要访问的地址
            driver.get(url);
            Thread.sleep(2000);
            //获取高度和宽度一定要在设置URL之后,不然会导致获取不到页面真实的宽高;
            Long width = (Long)driver.executeScript("return document.documentElement.scrollWidth");
            Long height =(Long) driver.executeScript("return document.body.parentNode.scrollHeight");
            System.out.println("高度:"+height);
            /*//这里按照网页需求有些是滑动的时候才加在的,如ajax的异步加载
            long temp_height = 0;
            while (true) {
                //每次滚动500个像素,因为懒加载所以每次等待2S 具体时间可以根据具体业务场景去设置
                driver.executeScript("window.scrollBy(0,500)");
                temp_height += 500;
                if(temp_height>=height){
                    break;
                }
            }*/
            //设置窗口宽高,设置后才能截全
            driver.manage().window().setSize(new Dimension(width.intValue(), height.intValue()));
            File srcFile = driver.getScreenshotAs(OutputType.FILE);
            // 这里的需求是将图片转为Base64码后换回,实际按需求控制
            inputFile = new FileInputStream(srcFile);
            byte[] buffer = new byte[(int)srcFile.length()];
            inputFile.read(buffer);
            String content = new BASE64Encoder().encode(buffer);
            return content;

            //设置截图文件保存的路径
            //String screenshotPath = "C:\wenjian\YA\imgGG1.png";
            //FileUtils.copyFile(srcFile, new File(screenshotPath));
        }catch (Exception e){
            e.printStackTrace();
            log.error("截图失败:"+e);
            return null;
        }finally {
            try{
                if (inputFile != null){
                    inputFile.close();
                }
            }catch (Exception ee){

            }
            if (driver!= null){
                driver.quit();
                service.stop();
            }
        }
    }