当前位置: 首页 > 知识库问答 >
问题:

硒铬屏幕截图-html2canvas

穆文斌
2023-03-14

我在使用html2canvas。js库,用于与selenium一起拍摄全页屏幕截图。

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();
        }
    }
}

我保存了html2canvas。我的java项目的类路径中的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浏览器拍摄整页屏幕截图。

共有2个答案

司空思聪
2023-03-14

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

在同源策略下,web浏览器允许网页中包含的脚本访问另一网页中的数据,前提是两个网页具有相同的源。因此,脚本使用的所有图像都需要位于同一原点下,以便能够读取它们。但在您的情况下,图像会加载到flipkart中。来自不同域的comhttp://img5a.flixcart.com(您可以通过flipkart中图像的src属性来验证这一点)

您的另一个选择是使用代理,但目前没有用于java的html2画布代理。如果您绝对需要,您可以构建一个。

其他解决方案,如果您感兴趣

伪代码

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)
}

最后,将所有屏幕截图连接到单个图像文件

希望这能帮助你。。。如果您有任何疑问,请返回

端木承业
2023-03-14

您可以使用以下内容。
但您必须处理一些等待,直到加载所有图像。
它可以选择跳过重复元素,因为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"));

UTIL。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();
}
}
 类似资料:
  • 在Linux下有很多屏幕载图的工具,下面简单介绍一下: 在GNOME桌面中自带了一个屏幕截图工具,位于“动作”栏内。该工具功能很少,只能截取当前屏幕。 在GMIP中也可截图,在“文件”--“获取”菜单下有一个“屏幕抓图”选项可进行屏幕截图。它可截取任意图窗口的内容,并自动输入到GMIP中,我们可方便地进行处理和保存。 安装ImageMagick软件,它有一个工具叫import可用于屏幕截图。该工具

  • 点击按钮进行截屏,可以将截屏图像保存到相册中。 作者说:听说会和苹果的策略有冲突,应用如果上架可能会被拒绝。这个估计是看人品了吧。经过测试发现,如果先弹出对话框,然后再截屏,似乎并不能把对话框也给保存下来。 [Code4App.com]

  • 问题内容: 我正在尝试获取包含SKScene的视图的屏幕抓图。我使用的技术是: 这对于普通的UIViews效果很好,但是无论出于何种原因,它都忽略了SKScene中的所有精灵。 我不确定这是否是错误,或者Sprite Kit的渲染是否与UIGraphics分开。 问题:当适用于UIViews的方式似乎不适用于Sprite Kit或有人成功将UIGraphics上下文与Sprite Kit结合使用时

  • 我试图根据用户输入的坐标捕捉区域截图。基本上,用户在屏幕上点击得到x,y坐标,然后在其他地方点击另一对x,y坐标,然后将其放入一个矩形中,并使用机器人库创建屏幕截图。 我有的问题是,我得到了随机截图,这不是用户输入的坐标,我怎么能考虑包括0的坐标,因为矩形值必须超过1。 以下是我迄今为止的代码:

  • 原文:Screenshots 这里你会找到一些示例图和生成它们的代码。 简单绘图 这里是一个带有文本标签的基本的绘图: 源代码 子图示例 多个轴域(例如子图)可使用subplot()命令创建: 源代码 直方图 hist()命令自动生成直方图,并返回项数或者概率: 源代码 路径示例 你可以使用matplotlib.path模块,在maplotlib中添加任意路径: 源代码 mplot3d mplot

  • 当我使用Ashot和selenium来捕获特定webelement的屏幕截图时,它不起作用。我还附上了日志以供参考。 截图获取整个页面正在运行。 注意:我已经更新了最新的jar的评论中提到 Iam使用Chrome驱动程序、selenium 3.8.1独立jar、Ashot 1.5.2 jar。 } 错误消息: