Reputation: 1071
I'm running a series of automated GUI tests using Selenium in Java. These tests regularely takes screenshots using:
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();
}
}
This works excellently in Chrome and IE, however in firefox I keep getting large pieces of whitespace under the screenshots. I suspect that the whitespace is actually a part of the page itself, but normally hidden from view in the browser(the scrollbar stops before the whitespace). I did a quick test with
driver.get("http://stackoverflow.com/");
takeScreenshot("D:\\TestRuns\\stackoverflow.png", driver);
and found that when using the Firefox driver the entire page in captured in the screenshot, while with the Chrome driver only what's shown in the browser is captured.
Is there any way to force the Firefox driver to take a screenshot containing ONLY what can actually be seen in the browser (what an actual user would see)?
Upvotes: 1
Views: 1413
Reputation: 1071
Based on answers from this question I was able to add 4 lines of code to just crop the image down to the browser size. This does solve my problem, although it would have been nicer if it could be solved through the driver instead of cropping after the screenshot has been taken.
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();
}
}
Upvotes: 2
Reputation: 105
Try this :
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);
}
}
Upvotes: 0