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进行截图,我遇到了一些页面加载很慢的,截的图可能不全或者是截不出图,目前还没更好的解决方案。如果大家有可以给我留言哦!

相关推荐
程序员黑豆1 小时前
Java包装类:基本类型与对象的桥梁
java·前端·ai编程
mldong5 小时前
"applicant" 契约:退回发起人的闭环设计
java·架构
月华路5 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
gugucoding6 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
zww89491116 小时前
校园跑腿系统开发实战指南:从需求分析到上线部署全流程解析
java
Fluxart.ai6 小时前
电商商品图审核怎么自动化?规则引擎、人工复核与发布门禁
java·前端·自动化
名字还没想好☜7 小时前
Java 线上内存泄漏排查实战:jmap 导堆、MAT 找 GC Roots 与四类常见泄漏
java·开发语言·jvm·内存泄漏
IT爱学堂9 小时前
尚硅谷 - 2025年3月Java+AI大模型应用开发
java·开发语言·人工智能
小贤plus10 小时前
SpringBoot 三大核心注解精讲:@ControllerAdvice、@RestControllerAdvice、@Validated 分组校验(实战)
java
吠品10 小时前
Java byte数组与String互转:编码细节与踩坑记录
java·linux·服务器