【问题标题】:How to make Selenium firefox driver take screenshots of only viewed page如何让 Selenium firefox 驱动只截取浏览过的页面
【发布时间】:2016-01-05 17:58:18
【问题描述】:

我正在使用 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 驱动程序截取屏幕截图,其中只包含浏览器中实际可以看到的内容(实际用户会看到的内容)?

【问题讨论】:

    标签: java selenium selenium-firefoxdriver


    【解决方案1】:

    根据this question 的回答,我能够添加 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();
        }
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      • 没用。仍然获得显示整个页面的屏幕截图,而不仅仅是在浏览器中看到的内容。
      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-02
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多