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

环境准备
Wondows服务器或电脑
本机需安装Chrome谷歌浏览器,根据本机浏览器版本,下载对应的chromedriver版本,chromedrive插件下载地址: 谷歌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();
            }
        }
    }

工具2

全面截屏
 //配置本地的chromediver.exe谷歌的内核
         System.setProperty("webdriver.gecko.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
         //设置ChromeOptions打开方式,设置headless:不弹出浏览器
         //设置好使用ChromeDriver使用
         ChromeDriver driver = new ChromeDriver();    
        
         driver.get("https://www.jianshu.com/u/a2b05c68b03b");
        
         //设置浏览器弹窗页面的大小
         driver.manage().window().maximize();
         //使用getScreenshotAs进行截取屏幕
            File srcFile = driver.getScreenshotAs(OutputType.FILE);  
            FileUtils.copyFile(srcFile, new File("G:\\pyChar\\jj.png")); 
   长截屏
    //配置本地的chromediver.exe谷歌的内核
         System.setProperty("webdriver.gecko.driver", "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe");
         //设置ChromeOptions打开方式,设置headless:不弹出浏览器
         ChromeOptions options = new ChromeOptions();
         options.addArguments("headless");
         //设置好使用ChromeDriver使用
         ChromeDriver driver = new ChromeDriver(options);    
         //获取要截图的地址,注:需要先获取地址哦,不然下方获取的宽度高度就会是弹窗的高和宽,而不是页面内容的高宽
         driver.get("https://www.jianshu.com/u/a2b05c68b03b");
         //获取页面高宽使用:return document.documentElement.scrollWidth
         //Long width = (Long)driver.executeScript("return document.documentElement.scrollWidth");
        // Long height =(Long) driver.executeScript("return document.documentElement.scrollHeight");
        Long width = (Long) ((JavascriptExecutor)driver).executeScript("return document.documentElement.scrollWidth");
        Long height = (Long) ((JavascriptExecutor)driver).executeScript("return document.documentElement.scrollHeight");
         //设置浏览器弹窗页面的大小
         driver.manage().window().setSize(new Dimension(width.intValue(), height.intValue()));
         //使用getScreenshotAs进行截取屏幕
            File srcFile = driver.getScreenshotAs(OutputType.FILE);  
            FileUtils.copyFile(srcFile, new File("G:\\pyChar\\jj.png"));    


元素截图使用方法
 WebElement findElementByXPath = ToolDriver.findElement(By.xpath("//*[@id=\"s_lg_img\"]"));
     
     File screenshotAs = findElementByXPath.getScreenshotAs(OutputType.FILE);
     String prName = "src/main/resources/" + "Toolimg" + ".png";
     try {
         FileUtils.copyFile(screenshotAs, new File(prName));
        
     } catch (IOException e) {
         e.printStackTrace();
       
     }
--全面截图再截图
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
WebElement element = driver.findElement(By.xpath("//div[@class='msn']"));
 Rectangle rect = element.getRect();
BufferedImage subImage= ImageIO.read(src).getSubimage(rect.x, rect.y, rect.getWidth(), rect.height);
ImageIO.write(subImage, "png", src);

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部