Scientech Easy How to Take Screenshot in Selenium WebDriver | Scientech Easy

Friday, April 12, 2019

How to Take Screenshot in Selenium WebDriver

Capturing the 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. So, 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 software tester tests any application, may be many of the functionalities not working compared to the expected result. So, tester logs these defects and tell the developers about the getting of defects in the code and suggest to fix 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 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 to identify web elements on the web page.
6. Timeout to find web elements on the web page.

Steps to capture the Screenshots using Selenium WebDriver


There are three easy steps to capture the screenshot using selenium web driver. 
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 code 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.
      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.
     FileUtils.copyFile(SrcFile, DestFile); 
Let's create a test that will open our login facebook page and take a screenshot of the page in PNG format.
Program source code:
    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. 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 web driver object to 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 destination. FileUtils.copyFile(scrFile, desFile); System.out.println("Taking Screenshots"); driver.close(); } }
    Output: Taking Screenshots PASSED: takeScreenshot =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 ===============================================
Screenshot imge file in png format
How to take screenshot in selenium webdriver

How to Take Screenshot for Failed Test cases in Selenium WebDriver


Now suppose that if a test case fails so how would we know where is the error or exception in the script. The Solution of 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. 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 implement this whole technique in the example program.
Program source 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{ WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); try{ String url="https://www.facebook.com"; driver.get(url); // Now we will find xpath of first name element in the facebook login page. // WebElement element=driver.findElement(By.xpath("//input[@name='firstname']")); // Statement with correct Xpath. WebElement element=driver.findElement(By.xpath("//input[@name='first']")); // Statement with incorrect Xpath. So, the control of execution will be transferred immediately to catch block. element.sendKeys("Shubh"); // This statement will not be executed due to occurring exception in the above statement. } // try block end here. catch(Exception e){ // Place the code inside 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(); } }
Final words 
Hope that this tutorial will help you to understand the concept of how to take screenshot in selenium webdriver step by step. We hope that you will have enjoyed this article.
Thanks for reading!