Take a Screenshot with Selenium WebDriver using Java

Typically when running Selenium WebDriver tests, you may need to take a screenshot to either confirm an action is working correctly or, if something has thrown an exception, to provide a visual confirmation of the error. The following is an example of the method I wrote and use for my tests, and I'll break this down into its components.

public static void takeAScreenshot(String name, WebDriver driver) throws Exception {
	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	LocalDateTime date = LocalDateTime.now();
	String formattedDateTime = date.format(formatter);
	File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
	FileUtils.copyFile(scrFile, new File(screenshotLocation + "/" + name + "_" + formattedDateTime + ".png"));
}

The variables:

String name
WebDriver driver
DatetimeFormatter formatter
LocalDateTime date
String formattedDateTime
String screenshotLocation

An example of how this could be invoked is thus:

if (selectedTabCount != expectedTabCount) {
	WebUtil.takeAScreenshot(driver, "Selected_tab_counts_dont_match");
	Assert.fail("Selected tab counts do not match");
}

This function creates a PNG-type screenshot based on the name of the string I passed and the system's date/time recorded. Additionally, it's copied to the location that I specify with the variable of 'screenshotLocation'.

Let's look at the input parameters.

The 'String name' is the name of the screenshot that's going to be saved. The 'WebDriver driver' is the webdriver component that's needed for the screenshot functionality to work.

The 'DatetimeFormatter formatter' is the variable for how the date time string is going to look. 'LocalDateTime date' is the system time now. 'String formattedDatetime' is the string used in the screenshot function to append to the name passed by the user.

The 'String screenshotLocation' is the location of where the screenshot is going to be put. My caveat to this is that I normally create screenshots within the target directory (ie. "target/screenshot"). The 'target' directory is where the compiled classes are stored, such as within a Maven setup. See the screenshot below of an actual output:

The reason to create these files within the target directory is that they will be cleaned up/destroyed when a 'mvn clean' command is issued and will not clutter your computer unnecessarily. Second, if you're using a Jenkins automated deployment, items within the target directory can be archived as test artifacts for that run. Screenshot below:

Also, please note that you'll need to add the ".png" to the end of the screenshot name in order for these to be recognized as PNG-type files more easily.

Hope this helps, and Happy automating!

To view or add a comment, sign in

More articles by Edward O'Hare Jr

Others also viewed

Explore content categories