chromedriver+Selenium+springboot+Java实现后端截图

chromedriver这种方法实现截图,依赖服务器端的谷歌浏览器软件,需要在服务器端下载谷歌浏览器。

Windows服务器说明

1.下载谷歌浏览器

2.根据第一步下载的谷歌浏览器版本,下载chromedriver,可以在这个页面找到和版本相近的版本去下载https://googlechromelabs.github.io/chrome-for-testing/

3.下载之后进行解压,将chromedriver.exe放到适合目录下

centos linux服务器说明

1.安装谷歌浏览器

java 复制代码
yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm

2.查看浏览器版本

java 复制代码
google-chrome --version

3.去https://googlechromelabs.github.io/chrome-for-testing/上面下载最接近的chromedriver。可以下载好放到服务器上,也可以通过下面命令下载(以我安装的120版本为列)

java 复制代码
wget https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/120.0.6099.109/linux64/chromedriver-linux64.zip

4.解压chromedriver-linux64.zip

java 复制代码
unzip chromedriver-linux64.zip

5.进入解压后的目录,查询chromedriver是否具有可执行权限,没的话记得赋权,之后记得chromedriver所在的目录路径,代码中需要

至此,安装完成,接下来进行Java代码开发

pom.xml中添加下面依赖

java 复制代码
<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>

CutPictureController.java

java 复制代码
 @GetMapping("/getCutPictureBySelenium")
    public void getCutPictureBySelenium(String url, String token,HttpServletResponse response) {
        cutPictureService.getCutPictureBySelenium(url,token,response) ;
    }

CutPictureService.java

@Value("${chromedriverPath}")

private String chromedriverPath;//在配置文件中进行路径配置

java 复制代码
public void getCutPictureBySelenium(String url, String token,HttpServletResponse response) {
        //这里设置下载的驱动路径,Windows对应chromedriver.exe Linux对应chromedriver,具体路径看你把驱动放在哪
        System.setProperty("webdriver.chrome.driver", chromedriverPath);
        ChromeOptions options = new ChromeOptions();
        //ssl证书支持
        options.setCapability("acceptSslCerts", true);
        //截屏支持
        options.setCapability("takesScreenshot", true);
        //css搜索支持
        options.setCapability("cssSelectorsEnabled", true);
        options.setPageLoadStrategy(PageLoadStrategy.NORMAL);

        //设置浏览器参数
        options.addArguments("--headless");
        options.addArguments("--disable-gpu");
        options.addArguments("--no-sandbox");
        options.addArguments("lang=zh_CN.UTF-8");
        options.addArguments("--disable-dev-shm-usage");
        //指定浏览器分辨率
        options.addArguments("window-size=1920x1080");


        options.setHeadless(true);
        ChromeDriver driver = new ChromeDriver(options);
        //设置超时,避免有些内容加载过慢导致截不到图
        driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.MINUTES);
        driver.manage().timeouts().implicitlyWait(3, TimeUnit.MINUTES);
        driver.manage().timeouts().setScriptTimeout(3, TimeUnit.MINUTES);
        try {
            //设置需要访问的地址
            driver.get(url);
            //进行cookie的设置,我这里是用于跳过登录
            Cookie c1 = new Cookie("admin-token",token);
            Cookie c2 = new Cookie("Authentication",token);
            driver.manage().addCookie(c1);
            driver.manage().addCookie(c2);
            //获取高度和宽度一定要在设置URL之后,不然会导致获取不到页面真实的宽高;
            Long width = (Long)driver.executeScript("return document.documentElement.scrollWidth");
            Long height =(Long) driver.executeScript("return document.documentElement.scrollHeight");
            System.out.println("高度:"+height);
            //这里需要模拟滑动,有些是滑动的时候才加在的
            long temp_height = 0;
            while (true) {
                //每次滚动500个像素,因为懒加载所以每次等待1S 具体时间可以根据具体业务场景去设置
                Thread.sleep(1000);
                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);

            FileInputStream fis = new FileInputStream(srcFile);


//            String screenshotPath = "D:\\imgghh.png";
//            FileUtils.copyFile(srcFile, new File(screenshotPath));

            //给前端放回流,可以进行下载,或者用上面注释的两行,将图片下载到本地
            response.setHeader("Content-Disposition","attachment;filename=test.jpg");
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) != -1) {
                out.write(buffer,0,length);
            }
            out.close();
            fis.close();
        }catch (Exception e){
            throw new RuntimeException("截图失败",e);
        }finally {
            driver.quit();
        }
    }

之后就可以执行程序,设置想截图的网页url进行截图,我遇到了一些页面加载很慢的,截的图可能不全或者是截不出图,目前还没更好的解决方案。如果大家有可以给我留言哦!

相关推荐
非 白5 分钟前
【Java分布式】Nacos注册中心
java·开发语言·nacos·注册中心
吃海鲜的骆驼11 分钟前
服务异步通讯与RabbitMQ
java·分布式·后端·rabbitmq
羱滒14 分钟前
sql调优之数据库开发规范
java·数据库·数据库开发
m0_7482386321 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
Forget the Dream43 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek1 小时前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
Forget the Dream2 小时前
设计模式之代理模式
java·c++·设计模式·代理模式