Selenium Chrome截图 - html2canvas

时间:2015-07-22 12:18:16

标签: java google-chrome selenium selenium-webdriver html2canvas

我正在使用html2canvas.js库来获取整页屏幕截图和硒。

public class ChromeCanvasCapture {

    private static final String APP_URL = "http://www.flipkart.com";

    public static String getFileContent(String filePath)
        throws FileNotFoundException, IOException {
        FileInputStream inputStream = new FileInputStream(filePath);
        String fileContent = IOUtils.toString(inputStream);
        inputStream.close();
        return fileContent;
    }

    public static void main(String[] args) {

        WebDriver webDriver = null;

        try {
            System.setProperty("webdriver.chrome.driver",
                "D:\\Drivers\\chromedriver.exe");
            webDriver = new ChromeDriver();
            webDriver.get(APP_URL);
            webDriver.manage().window().maximize();

            if (webDriver instanceof JavascriptExecutor) {
                // scroll to the bottom of the page
                ((JavascriptExecutor) webDriver)                        .executeScript("window.scrollTo(0,document.body.scrollHeight)");
                // //scroll to the top of the page
                ((JavascriptExecutor) webDriver)
                    .executeScript("window.scrollTo(0,0)");
            }

            String jsFile = getFileContent("html2canvas.js");
            jsFile = jsFile
                + " var webDriverCallback = arguments[arguments.length - 1]; html2canvas(document.body, {onrendered: function(canvas) {var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');; webDriverCallback(img); }";
            System.out.println(jsFile);
            webDriver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
            if (webDriver instanceof JavascriptExecutor) {
                JavascriptExecutor executor = (JavascriptExecutor) webDriver;
                Object result = executor.executeAsyncScript(jsFile);
                String imageString = String.valueOf(result);
                byte[] imageData = Base64.decodeBase64(imageString);
                OutputStream outputStream = new FileOutputStream(
                    "C:\\Captures\\canvas_captured.png");
                outputStream.write(imageData);
                outputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // webDriver.quit();
        }
    }
}

我在我的java项目的类路径中保存了html2canvas.js文件。我用来获取屏幕截图的java脚本代码是:

var webDriverCallback = arguments[arguments.length - 1];

html2canvas(document.body, {
    onrendered: function(canvas) {
        var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');;
        webDriverCallback(img);
    }
});

我可以捕捉flipkart页面的整页屏幕截图,但不包含任何图像。

我无法使用Chrome中的TakeScreenshot实用程序,因为它不允许使用Chrome浏览器拍摄整页屏幕截图。

Screenshot using canvas2html.js

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容 但是你需要等待所有图像加载 它可以选择跳过重复元素,因为flipkart的标题搜索横幅是重复元素,我将其作为要隐藏的元素传递。

    driver.get("http://www.flipkart.com");
    WebDriverWait wait = new WebDriverWait(driver, 60);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(@class,'fk-ui-ccarousel-supercontainer requirecss-HPS')]")));

    WebElement header = driver.findElement(By.id("fk-header"));
    //As header is repeating we are giving it as repetitive element so that it will remove it while taking screenshot
    Files.copy(Utils.makeFullScreenshot(driver, header), new File("D:\\fsile.png"));

<强> Utils.Java
这是对GalenFramework的FullPageScreenShot

的修改
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class Utils {

private static final String JS_RETRIEVE_DEVICE_PIXEL_RATIO = "var pr = window.devicePixelRatio; if (pr != undefined && pr != null)return pr; else return 1.0;";

private static void hideScroll(WebDriver driver) {
    ((JavascriptExecutor) driver).executeScript("document.documentElement.style.overflow = 'hidden';");
}

private static void showScroll(WebDriver driver) {
    ((JavascriptExecutor) driver).executeScript("document.documentElement.style.overflow = 'visible';");
}

private static void showHideElements(WebDriver driver, Boolean hide, WebElement... skipElements) {
    String display;
    if (hide) {
        display = "none";
    } else {
        display = "block";
    }
    if (skipElements != null) {
        for (WebElement skipElement : skipElements) {
            ((JavascriptExecutor) driver).executeScript("arguments[0].style.display = '" + display + "';", skipElement);
        }
    }
}

private static byte[] getScreenShot(WebDriver driver) {
    return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}

//The code that does the job
public static File makeFullScreenshot(WebDriver driver, WebElement... skipElements) throws IOException, InterruptedException {
    //Scroll to bottom to make sure all elements loaded correctly
    // scrollVerticallyTo(driver, (int) longScrollHeight);

    // scroll up first to start taking screenshots
    scrollVerticallyTo(driver, 0);
    hideScroll(driver);
    //No need to hide elements for first attempt
    byte[] bytes = getScreenShot(driver);

    showHideElements(driver, true, skipElements);
    long longScrollHeight = (Long) ((JavascriptExecutor) driver).executeScript("return Math.max("
            + "document.body.scrollHeight, document.documentElement.scrollHeight,"
            + "document.body.offsetHeight, document.documentElement.offsetHeight,"
            + "document.body.clientHeight, document.documentElement.clientHeight);"
    );

    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
    int capturedWidth = image.getWidth();
    int capturedHeight = image.getHeight();

    Double devicePixelRatio = ((Number) ((JavascriptExecutor) driver).executeScript(JS_RETRIEVE_DEVICE_PIXEL_RATIO)).doubleValue();

    int scrollHeight = (int) longScrollHeight;

    File file = File.createTempFile("screenshot", ".png");

    int adaptedCapturedHeight = (int) (((double) capturedHeight) / devicePixelRatio);

    BufferedImage resultingImage;

    if (Math.abs(adaptedCapturedHeight - scrollHeight) > 40) {
        int scrollOffset = adaptedCapturedHeight;

        int times = scrollHeight / adaptedCapturedHeight;
        int leftover = scrollHeight % adaptedCapturedHeight;

        final BufferedImage tiledImage = new BufferedImage(capturedWidth, (int) (((double) scrollHeight) * devicePixelRatio), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2dTile = tiledImage.createGraphics();
        g2dTile.drawImage(image, 0, 0, null);

        int scroll = 0;
        for (int i = 0; i < times - 1; i++) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(new ByteArrayInputStream(getScreenShot(driver)));
            g2dTile.drawImage(nextImage, 0, (i + 1) * capturedHeight, null);
        }
        if (leftover > 0) {
            scroll += scrollOffset;
            scrollVerticallyTo(driver, scroll);
            BufferedImage nextImage = ImageIO.read(new ByteArrayInputStream(getScreenShot(driver)));
            BufferedImage lastPart = nextImage.getSubimage(0, nextImage.getHeight() - (int) (((double) leftover) * devicePixelRatio), nextImage.getWidth(), leftover);
            g2dTile.drawImage(lastPart, 0, times * capturedHeight, null);
        }

        scrollVerticallyTo(driver, 0);

        resultingImage = tiledImage;
    } else {
        resultingImage = image;
    }
    showScroll(driver);
    showHideElements(driver, false, skipElements);
    ImageIO.write(resultingImage, "png", file);
    return file;
}

private static void scrollVerticallyTo(WebDriver driver, int scroll) {
    ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, " + scroll + ");");
    try {
        waitUntilItIsScrolledToPosition(driver, scroll);
    } catch (InterruptedException e) {
       // LOG.trace("Interrupt error during scrolling occurred.", e);
    }
}

private static void waitUntilItIsScrolledToPosition(WebDriver driver, int scrollPosition) throws InterruptedException {
    int hardTime = 0;//SCREENSHOT_FULLPAGE_SCROLLWAIT
    if (hardTime > 0) {
        Thread.sleep(hardTime);
    }
    int time = 250;//SCREENSHOT_FULLPAGE_SCROLLTIMEOUT
    boolean isScrolledToPosition = false;
    while (time >= 0 && !isScrolledToPosition) {
        Thread.sleep(50);
        time -= 50;
        isScrolledToPosition = Math.abs(obtainVerticalScrollPosition(driver) - scrollPosition) < 3;
    }
}

private static int obtainVerticalScrollPosition(WebDriver driver) {
    Long scrollLong = (Long) ((JavascriptExecutor) driver).executeScript("return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;");
    return scrollLong.intValue();
}
}

答案 1 :(得分:0)

html2canvas 脚本通过遍历页面的DOM来工作它收集那里所有元素的信息,然后用它来构建页面的表示,这意味着它实际上没有截取屏幕截图页面,但通过读取DOM构建表示即ie)整个图像在客户端浏览器上创建,因此它不会绕过任何浏览器内容策略限制

在相同的原始策略下,Web浏览器允许网页中包含的脚本访问来自其他网页的数据,仅当两个网页具有相同的来源时才提供。因此,脚本使用的所有图像都需要位于相同的原点以便能够读取它们。但在您的情况下,图像将从flipkart.com中从不同的域http://img5a.flixcart.com加载(您可以从flipkart中图像的src属性

你拥有的另一个选择是使用代理但目前没有用于java的html2canvas proxy。如果你绝对需要你可以构建一个。

如果您有兴趣,可以使用其他解决方案

<强>伪代码

document.documentElement.scrollHeight //gives total page height

document.documentElement.clientHeight //gives current screen height

//You can write ur logic ex : if scroll height is greater than client height scroll
if(document.documentElement.scrollHeight>document.documentElement.clientHeight)
//take screenshot and then scroll(Do this till the end of the page)
}

最后将所有屏幕截图加入单个图像文件

希望这可以帮助你...如果您有任何疑问,请回来