2

所以我正在尝试使用 selenium 截取当前页面的屏幕截图。

我看过代码示例,例如

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("location"));

但这仅在驱动程序被声明为FirefoxDriver 时才有效

FirefoxDriver driver = new FirefoxDriver();

对于我的程序,我需要使用HtmlUnitDriver

HtmlUnitDriver driver = new HtmlUnitDriver();

因为我想要无头浏览器,因为 FireFoxDriver 打开 firefox 然后做所有事情。

无论如何我可以使用 HtmlUniteDriver 截屏,或者无论如何我可以使用另一个但没有浏览器出现,所以它是无头的。

4

2 回答 2

1

One thing you could do is to create your own extended version of HtmlUnitDriver that does implement the TakesScreenshot interface.

class ExtendedHtmlUnitDriver extends HtmlUnitDriver implements TakesScreenshot {
  @Override
  public <X> X getScreenshotAs(OutputType<X> target) throws WebDriverException {
    final String base64 = execute(DriverCommand.SCREENSHOT).getValue().toString();
    return target.convertFromBase64Png(base64);
  }
}

Then you could do something like this:

HtmlUnitDriver driver = new ExtendedHtmlUnitDriver();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("location"));

This code is not complete but should be enough to show where to go.

于 2013-11-14T03:19:03.040 回答
1

虽然我自己还没有机会尝试这段代码,但我确实找到了 HtmlUnitDriver 的这个实现,它为你实现了截屏界面:

https://groups.google.com/forum/#!msg/selenium-developers/PTR_j4xLVRM/k2yVq01Fa7oJ

为了增加这段代码的功能,它允许您像通常使用其他 WebDriver(如 FireFox 或 Chrome)一样调用截屏方法,然后它将当前 html 页面和所有相关的 css 和图像转储到 zip 存档中。

以下是您如何从代码中调用它:

WebDriver driver = new ScreenCaptureHtmlUnitDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

希望这会有所帮助!

于 2014-04-17T13:50:00.200 回答