Taking Screenshot using Webdriver

Its very important to take screenshot when we execute a test script. When we execute huge number of test scripts, and if some test fails, we need to check why the test has failed.

It helps us to debug and identify the problem by seeing the screen shot.

In selenium webdriver, we can take the screen shot using the below command.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

NOTE: - If you are using latest version of selenium, please check this updated article Take Screenshot using FileHandler class

Check the framework example of Taking ScreenShot for ONLY Failed Tests using TestNG
The below example explains how to take the screen shot when the test fails.

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
    public class takeScreenShotExample{
        public WebDriver driver;
      public void openBrowser() throws Exception {
    	  driver = new FirefoxDriver();
                //the below statement will throw an exception as the element is not found, Catch block will get executed and takes the screenshot.
                   //if we remove the below comment, it will not return exception and screen shot method will not get executed.
    	  catch (Exception e){
    		  System.out.println("I'm in exception");
//calls the method to take the screenshot.
      public void getscreenshot() throws Exception 
              File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
           //The below method will save the screen shot in d drive with name "screenshot.png"
              FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));
Selenium Tutorials: 


Hi! I simply wish to offer you a huge thumbs up for your excellent information you have got here on this post.
I will be returning to your site for more soon.


With the above code i am getting exception. Can anybody solve this issue?

org.openqa.selenium.InvalidArgumentException: unknown error: cannot get automation extension

for the code
File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

As per below code. My URL's are driven from spreadsheet and I'm saving/capturing screenshots to a folder. So, first URL is www.google.com it capture but, for next iteration for another url it replaces previously captured screens ofcourse due to screen naming conventions. Is there a way to fix it? So, that I can capture unique screenshots for each run?

Thank you!!!!

You can attach time stamp or you can pass name for the screenshot as you are passing the URL.

Please explain meaning of writing ((TakesScreenshot)driver)

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.