How to Take Screenshot in Selenium WebDriver

In this tutorial, we will learn how to take a screenshot in Selenium WebDriver using Java.

Capturing screenshots for the test execution is one of the important scripts in the test automation, which helps us to identify bugs and problems by seeing the screenshot.

Selenium WebDriver provides a TakesScreenshot interface to capture a screenshot of the webpage when an exception or error occurred during the execution of code.

When a software tester tests any application, may be many of the functionalities not working compared to the expected result. So, the tester logs these defects and tells the developers about the getting of defects in the code, and suggests fixing the defects or bugs to retest once again.

But developers never accept a defect without required evidence and details. They need the required evidence to analyze the issues.

That’s why taking the screenshot is one of the mandatory pieces of evidence to view and understand why the test has failed. We can take the screenshot in image files like png, jpeg, or jpg.

There are some scenarios below you may need to capture the screenshot using selenium web driver.

1. Exception or error occurs during the execution of code.
2. Assertion failure.
3. To identify bugs or defects.
4. If some test fails when you execute a huge number of test scripts.
5. If you have difficulty identifying web elements on the web page.
6. Timeout to find web elements on the web page.

Steps to Take Screenshot using Selenium WebDriver


There are three easy steps to capture or take the screenshot in selenium webdriver using Java.

1. Since TakesScreenshot is an interface. So, we cannot create an object directly. We will have to convert the web driver object to TakesScreenshot.

The syntax to convert the WebDriver object to TakesScreenshot is given below:

TakesScreenshot scrShot = ((TakesScreenshot)webdriver);

2. Now we will call getScreenshotAs() method to create an image file which is provided by the TakesScreenshot interface to capture the screenshot of the web page displayed in the driver object.


The complete syntax is as follows:

File srcFile = scrShot.getScreenshotAs(OutputType.FILE);

Here, the argument “OutputType.FILE” specified in the getScreenshotAs() method will return the capture screenshot in the form of file. Therefore, we will store in the variable ‘srcFile’ with type File.

3. In the last step, save the file object returned by getScreenshotAs() method using copyFile() method of the FileUtils class. The syntax is given below:

FileUtils.copyFile(SrcFile, DestFile);

Let’s create a test where we will open the login Facebook page and take a screenshot of the page in PNG format. Look at the source code to understand better.

Program code 1:

package takeScreenshot; 
import java.io.File; 
import java.io.IOException; 
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.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.testng.annotations.Test; 

public class CaptureScreenshot { 
@Test 
public void takeScreenshot() throws IOException 
{ 
// Create an object of FirefoxDriver class. 
   WebDriver driver = new FirefoxDriver(); 

// Maximizing the browser windows. 
   driver.manage().window().maximize(); 

   String URL = "https://www.facebook.com"; 
   driver.get(URL); 

   WebElement element = driver.findElement(By.xpath("//input[@name='email']")); 
   element.sendKeys("Deepak");

// Convert a web driver object into TakeScreenshot. 
   TakesScreenshot ts = (TakesScreenshot)driver; 

// Call getScreenshotAs() method to create image file. 
   File scrFile = ts.getScreenshotAs(OutputType.FILE); 

// Create an object of the file to move the image file to the new destination and pass the file path as an argument. 
   File desFile = new File("./Screenshots/facebook.png"); 

// Call copyFile() method to save the file at the destination. 
   FileUtils.copyFile(scrFile, desFile); 
   System.out.println("Taking Screenshots"); 

// Close the browser.
   driver.close(); 
 } 
}
Output: 
      Taking Screenshots 
      PASSED: takeScreenshot 
      =============================================== 
      Default test Tests run: 1, Failures: 0, Skips: 0 
      ===============================================

Screenshot image file in png format:

How to take screenshot in Selenium WebDriver

How to Take a Screenshot of Failed Test Cases?


Now suppose that if a test case fails, so how would we know where is the error or exception in the script.


The Solution to this problem can be handled by capturing a screenshot of the webpage when the test case fails. By seeing the screenshot, you could easily identify where exactly the script got failed.

To capture the screenshot in the failed test steps, we will place the entire code in the try-catch block. Basically, a try block is a block of statements within which exception might occur. A catch block handles the exception thrown by try block. It will execute if an exception occurs within the try block otherwise not.

So, we will place the test steps in the try block and screen statements in the catch block. If a test step fails in the try block then the control of execution will be immediately transferred to the catch block.

When the statements of the catch block will be executed, it will capture the screenshot of the webpage. Let’s understand it with the help of an example.

Program code 2:

package takeScreenshot; 
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.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.testng.annotations.Test; 

public class CaptureScreenshot2 { 
@Test
public static void captureScreenMethod() throws Exception
{ 
 // Instantiate a Firefox driver and maximize the browser.
    WebDriver driver = new FirefoxDriver(); 
    driver.manage().window().maximize(); 

    try 
    { 
        String URL = "https://www.facebook.com"; 
        driver.get(URL); 

     // Find the XPath of the first name element in the Facebook login page. 
     // Statement with correct XPath.
     // WebElement element = driver.findElement(By.xpath("//input[@name='firstname']")); 

     // Statement with incorrect XPath. 
     // So, the control of execution will be transferred immediately to the catch block.  
        WebElement element = driver.findElement(By.xpath("//input[@name='first']"));  
    
     // This statement will not execute due to the occurring exception in the above statement.
        element.sendKeys("Shubh"); 
     } // try block end here. 
     catch(Exception e) 
     { 
     // Place the code inside the catch block for taking screenshot 
        TakesScreenshot ts=(TakesScreenshot)driver; 
        File scrFile = ts.getScreenshotAs(OutputType.FILE); 
    
        File desFile = new File("./Screenshots/facebook.png"); 
        FileUtils.copyFile(scrFile, desFile); 
        System.out.println("Taking Screenshots"); 
     } 
     driver.close(); 
     driver.quit(); 
   } 
}

In this tutorial, we have explained step-by-step guide to how to take screenshot in Selenium Webdriver with the help of examples. To take a screenshot in Selenium WebDriver using Java needs to utilize the TakesScreenshot interface provided by Selenium.

This interface has a method called getScreenshotAs() that allows us to capture a screenshot of the current window. Hope that you will have understood how to take a screenshot if test cases failed. In the next, we will understand Iframe in Selenium and how to switch to it.
Happy coding!!!
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love