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

相关推荐
二哈赛车手几秒前
新人笔记---简易版AI实现以图搜图功能
java·人工智能·笔记·spring·ai
夕除2 分钟前
spring boot 6
java·spring boot·后端
johnrui26 分钟前
JUC之AQS
java·开发语言·jvm
Full Stack Developme27 分钟前
Spring 模块介绍
java·后端·spring
多敲代码防脱发40 分钟前
Spring进阶(BeanFactory与ApplicationContext)
java·数据库·spring boot·后端·spring
吴声子夜歌1 小时前
Java——反射
java·反射
JAVA面经实录9171 小时前
完整版JVM 深度学习体系(二)
java·jvm
.ZGR.1 小时前
线程池相关知识及并发统计案例实现
java·开发语言
慕言手记1 小时前
IDEA 插件常用-2026版
java·ide·spring boot·intellij-idea·idea·intellij idea
颖火虫盟主1 小时前
Hello World MCP Server 实现总结
java·前端·python