java使用Chrome+Selenium+Screenshot 实现浏览器截长图

场景:需要长截图整个网站;

效果:
我进行了缩小和模糊处理,涉及到公司业务.模糊的可以看到是忽略了浏览器的头部,保留了完整的整个网页

解决思路:

  1. 模拟用户打开浏览器,然后截图,这边涉及到几个问题
    1. 浏览器打开网站需要一定的时间,这边怎么设置?
    2. 浏览器打开之后,如果网页长度过长,需要拉动滚轴,模拟用户浏览过程?怎么获取到浏览器的高度,每次滚轴滚的长度?
    3. 截图怎么保留?转换为图片流,并保存

pom.xml

  <!-- 截图插件 -->
        <dependency>
            <groupId>ru.yandex.qatools.ashot</groupId>
            <artifactId>ashot</artifactId>
            <version>1.5.4</version>
        </dependency>
<!-- selenum -->
  <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
        </dependency>

Chrome浏览器驱动http://chromedriver.storage.googleapis.com/index.html

import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.coordinates.WebDriverCoordsProvider;
import org.openqa.selenium.Platform;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
    
    /**
     * 截图
     *
     * @param domain          地址  https://www.baidu.com/
     * @param correlationId   图片附件保留关联id
     * @param rollingDistance 滚动距离 300
     * @param waitTime        滚动等待时间(毫秒) 500
     * @param implicitlyWait  浏览器等待时间
     * @return void
     * @date 2020/9/28 10:48
     * @author Dora
     **/
    public void screenshot(String domain, Long correlationId
            , int rollingDistance, long waitTime, long implicitlyWait, String fileName) {
        if (WebAssert.isAnyoneEmpty(domain, correlationId)) {
            throw new BusinessException("[域名|关联id]不能为空");
        }
        long o = System.currentTimeMillis();
        log.info("网站:{},截图-上传开始时间:{}", domain, o);
        WebDriver driver = this.createWebDriver();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            driver.manage().timeouts().implicitlyWait(implicitlyWait, TimeUnit.SECONDS);
            driver.manage().window().maximize();
            driver.get(domain);
            //等待页面加载完成
            new WebDriverWait(driver, 300).until(drive -> ((JavascriptExecutor) drive)
                    .executeScript("return document.readyState").equals("complete"));
            // 设置小的分辨率
            driver.manage().window().setSize(new Dimension(1920, 1080));
            JavascriptExecutor je = (JavascriptExecutor) driver;
            //    int width = Integer.parseInt(je.executeScript("return document.body.scrollWidth") + "");
            int height = Integer.parseInt(je.executeScript("return document.body.scrollHeight") + "");
            log.info("{},当前页面高度:{}", domain, height);
            // 滚动次数
            int frequency = height % rollingDistance == 0 ? height / rollingDistance : height / rollingDistance + 1;
            for (int i = 0; i < frequency; i++) {

                int length = i * rollingDistance;
                Thread.sleep(waitTime);
                ((JavascriptExecutor) driver).executeScript("window.scrollTo(0," + length + ")");
            }

            //设置浏览窗口大小
            driver.manage().window().setSize(new Dimension(1440, height));
            // 重新拉到页面顶端
            ((JavascriptExecutor) driver).executeScript("window.scrollTo(document.body.scrollHeight,0)");

            // 截图
            Screenshot screenshot = new AShot().coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver);
            BufferedImage image = screenshot.getImage();
          
            log.info("网站:{},截图-上传结束时间:{}", domain, System.currentTimeMillis() - o);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            
        }
        driver.quit();
    }

 public static WebDriver createWebDriver() {

        ChromeOptions options = new ChromeOptions();
        options.addArguments("test-type");
        options.addArguments("--disable-extensions--");
        options.addArguments("proxy=null");
        options.addArguments("--headless");
        options.addArguments("--window-size=1920,1080");
        options.addArguments("--ignore-certificate-errors");
        options.addArguments("--no-sandbox");
        options.addArguments("--incognito");
        DesiredCapabilities capability = DesiredCapabilities.chrome();
        capability.setBrowserName("chrome");
        capability.setPlatform(Platform.LINUX);
        try {
            driver = new RemoteWebDriver(new URL(CHROME_DRIVER_PATH), capability);
        } catch (MalformedURLException e) {
            logger.error("driver异常:{}", e);
        }
        return driver;

    }

注意:chrome内核如果用的是windows版本 会出现这种导航重复的效果,一定要用Linunx的内核版本才能出现截长图的效果
 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页