Selenium / Java-拍摄整页截图

时间:2019-05-17 08:29:13

标签: java selenium

开箱即用,Webdriver只截取可见页面区域的屏幕截图。 从this post开始,我想问一下,当页面长度大于视口时,如何使用Java在Selenium中拍摄完整的屏幕截图?

描述如何执行此操作的帖子未得到回答(例如this one),或者指向提供该功能的AShot库(例如this one),但是它具有一些功能这意味着我不想使用它。具体来说,当使用远程驱动程序时,例如Browserstack,仅呈现屏幕截图的左半部分。此外,它不再由原始作者维护,因此对于本质上很简单的问题,写一个新函数似乎更合适。

1 个答案:

答案 0 :(得分:2)

先决条件:访问WebDriver的实例。我的实例使用代码所在的类实例化。

协调屏幕截图大小和向下滚动页面的主要功能如下。请注意,图像格式应使其与pdiff兼容:

public void takeFullScreenshot(String outputFile) throws IOException {


        JavascriptExecutor js = ((JavascriptExecutor) webDriver);

        // Scroll right to the top
        js.executeScript("window.scrollTo(0,0)");

        // Get the height of the screen
        int windowHeight = ((Number) js.executeScript("return window.innerHeight")).intValue();

        // Get the total height of the page
        int pageHeight = ((Number) js.executeScript("return document.body.scrollHeight")).intValue();

        // Calculate the number of full screen shots
        double fullFraction = pageHeight / windowHeight;
        int fullShots = (int) fullFraction; // this simply removes the decimals

        // Initialise ouput image
        int imageWidth = webDriver.manage().window().getSize().width;
        BufferedImage fullScreenshot = new BufferedImage(imageWidth, pageHeight, BufferedImage.TYPE_4BYTE_ABGR);

        // Get the graphics
        Graphics2D fullGraphics = fullScreenshot.createGraphics();

        // Calculate our scroll script
        String script = "window.scrollBy(0," + String.valueOf(windowHeight) + ")";

        // Loop - for the required number of full screenshots
        for (int aShot = 0; aShot < fullShots; aShot ++) {

            // Sort out the screenshot and paste it in the correct place
            pasteScreenshot(fullGraphics, aShot * windowHeight);

            // scroll
            js.executeScript(script);
        }

        // Final phase - scroll to the bottom
        js.executeScript(script); // we know this goes too far down, but should be OK.

        // Take final screenshot and paste at the bottom
        pasteScreenshot(fullGraphics, pageHeight - windowHeight);

        // Save the whole thing to output file.
        ImageIO.write(fullScreenshot, "PNG", new File(outputFile));
    }

将屏幕截图粘贴到输出图形中正确位置的小功能如下:

private void pasteScreenshot (Graphics2D outputGraphics, int yCoordinate) throws IOException {
        // Take screenshot and hold it as an image
        File tmpFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        BufferedImage tmpImage = ImageIO.read(tmpFile);

        // Draw it on the graphics of the final output image
        outputGraphics.drawImage(tmpImage, null, 0, yCoordinate);

    }

希望这很有用。