How to capture Screenshot of webpage using WebDriver with Java

While testing an application manually, we have a physical machine to work on and we can easily diagnose where exactly the test case has failed. But, it is not the case with automation testing.

Our automation script might be running on some remote machine (if integrated with CI tool), and we might not have access to check what is going wrong with the application.

So in this scenario, you need to capture the screenshot of the screen and save at some specified location, from where you can check the status of the web page.

We can achieve this using TakesScreenshot interface provided by WebDriver API.

Methods of TakesScreenshot interface :

getScreenshotAs method:

Usage : Used to take the screenshot of the current screen.

Syntax : getScreenshotAs (OutputType<X> target)

Return type : X <x>

Parameters : target – Check the options provided by OutputType

Applicability : Not specific to any DOM element

Example :

TakesScreenshot screenshot = (TakesScreenshot) driver;

File file = screenshot.getScreenshotAs(OutputType.FILE);

Since, TakesScreenshot is an interface, it does not provide implementation of the stated method.

RemoteWebDriver is class which implements TakesScreenshot interface provides implementation of the method.

public class RemoteWebDriver implements TakesScreenshot

Now, lets have a look at the code snippet.

public class TakeScreenShotDemo {

public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();

                  // casting driver instance to TakeScreenshot interface.
TakesScreenshot screenshot = (TakesScreenshot) driver;

                  // calling getScreenshotAs method with output paramater as File
File file = screenshot.getScreenshotAs(OutputType.FILE);

                  // creating a destination file
File destination = new File(“newFilePath(e.g.: C:\\Folder\\Desktop\\snapshot.png)”);
try {

                         // copying captured snapshot in destination file 
FileUtils.copyFile(file, destination);
} catch (IOException e) {


And that is it. You can check the captured snapshot at specified path.

Visit How to take screenshot of failed test cases?

Hope it helps you!

Cheers 🙂


#screenshot-in-webdriver, #webdriver