Java 如何让Selenium firefox驱动程序拍摄仅查看页面的屏幕截图

Java 如何让Selenium firefox驱动程序拍摄仅查看页面的屏幕截图,java,selenium,selenium-firefoxdriver,Java,Selenium,Selenium Firefoxdriver,我正在Java中使用Selenium运行一系列自动化GUI测试。这些测试通常使用以下方式拍摄屏幕截图: public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) { File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { F

我正在Java中使用Selenium运行一系列自动化GUI测试。这些测试通常使用以下方式拍摄屏幕截图:

    public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
这在Chrome和IE中表现出色,但在firefox中,我总是在屏幕截图下看到大量空白。我怀疑空白实际上是页面本身的一部分,但通常在浏览器中是隐藏的(滚动条在空白之前停止)。我做了一个快速测试

    driver.get("http://stackoverflow.com/");
    takeScreenshot("D:\\TestRuns\\stackoverflow.png", driver);
并发现,当使用Firefox驱动程序时,屏幕截图中会捕获整个页面,而使用Chrome驱动程序时,只会捕获浏览器中显示的内容

有没有办法强迫Firefox驱动程序拍摄一个屏幕截图,其中只包含浏览器中实际可以看到的内容(实际用户会看到的内容)?

尝试以下方法:

private static void snapshotBrowser(TakesScreenshot driver, String screenSnapshotName, File browserFile) {
        try {

            File scrFile = driver.getScreenshotAs(OutputType.FILE);
            log.info("PNG browser snapshot file name: \"{}\"", browserFile.toURI().toString());

            FileUtils.deleteQuietly(browserFile);
            FileUtils.moveFile(scrFile, browserFile);
        } catch (Exception e) {
            log.error("Could not create browser snapshot: " + screenSnapshotName, e);
        }
    }
根据我的回答,我可以添加4行代码,将图像裁剪到浏览器大小。这确实解决了我的问题,不过如果可以通过驱动程序解决问题,而不是截图后裁剪,那会更好

public static void takeScreenshot(String screenshotPathAndName, WebDriver driver) {
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    try {

        int height = driver.manage().window().getSize().getHeight();
        BufferedImage img = ImageIO.read(scrFile);
        BufferedImage dest = img.getSubimage(0, 0, img.getWidth(), height);
        ImageIO.write(dest, "png", scrFile);

        FileUtils.copyFile(scrFile, new File(screenshotPathAndName));
    } catch(Exception e) {
        e.printStackTrace();
    }
}

没用。仍然可以看到显示整个页面的屏幕截图,而不仅仅是浏览器中显示的内容。