How to Capture Screenshot in Selenium Webdriver


In Automation, it is advisable to take screenshots of failed test cases for further analysis and proof of failure. Selenium provides the capability to take screenshot. But, before we see how to capture Screenshot in Selenium, we need to add a dependency in the Maven project.

Recently Selenium has done some changes in recent version so if you are using Selenium 3.6.0 then you need to add below jar to project or if you are using then you can provide below dependency in project.

To capture a screenshot in Selenium, we can make use of an interface, called TakesScreenshot. This method indicates the driver, that it can capture a screenshot and store it in different ways

TakesScreenshot ts = (TakesScreenshot) driver;

In order to capture screenshot and store it in a particular location, there is a method called “getScreenshotAs“, where OutputType defines the output type for a screenshot.

File source = ts.getScreenshotAs(OutputType.FILE);

Copy file to Desired Location

FileUtils.copyFile(source, newFile("./Screenshots/Selenium" + System.currentTimeMillis() + ".png"));

Let’s see the complete program

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class ScreenshotDemo {
      public static void main(String[] args) throws IOException {
          System.setProperty("", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
          WebDriver driver = new ChromeDriver();
          // Maximize the window
          // Convert web driver object to TakeScreenshot
          TakesScreenshot ts = (TakesScreenshot) driver;
          // Call getScreenshotAs method to create image file
           File source = ts.getScreenshotAs(OutputType.FILE);
          // Copy file at destination
          FileUtils.copyFile(source, new File("./Screenshots/Selenium" + System.currentTimeMillis() + ".png"));
           System.out.println("the Screenshot is taken");
          // close the current browser

A folder with name Screenshots created and the screenshot is placed in that folder as you can see the image below

The Screenshot looks like something below

If you don’t want to use Maven Dependency common-io, then you can use FileHandler from

FileHandler.copy(source, new File("C:\\Screenshots\\Selenium" + System.currentTimeMillis() + ".png"));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s