Reputation: 1129
So I'm trying to take a screenshot of the current page using selenium.
I have seen examples of code such as
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("location"));
But this only works when the driver is declared as a FirefoxDriver
FirefoxDriver driver = new FirefoxDriver();
For my program I need to use HtmlUnitDriver
HtmlUnitDriver driver = new HtmlUnitDriver();
Because I'd like to have the headless browser, as the FireFoxDriver opens firefox and then does everything.
Is there anyway I can either take a screenshot using the HtmlUniteDriver or is there anyway I can use the other one but without the browser showing up so it's headless.
Upvotes: 3
Views: 4117
Reputation: 286
While I haven't had a chance to try this code yet myself, I did find this implementation of HtmlUnitDriver that implements the take screenshot interface for you:
https://groups.google.com/forum/#!msg/selenium-developers/PTR_j4xLVRM/k2yVq01Fa7oJ
To add a little more to what this code does, it allows you to call the take screenshot method as you normally would with other WebDrivers such as FireFox or Chrome and then it dumps current html page and all related css and images into zip archive.
Here is how you would call this from your code:
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"));
Hope this helps a little more!
Upvotes: 0
Reputation: 1969
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.
Upvotes: 1