How to capture Screen Shot in Selenium

Why Screen shots are required?
  • When application issues occur
  • When an assertion failure occurs
  • It is helpful to track the execution when working with headless browser.
  • It helps us to understand the flow of the application.
  • For cross browser testing.
  • When there is some difficulty in finding web elements on a page
  • Where there is a Timeout in finding web elements on a web page
Screenshots are desirable for bug analysis. Selenium can automatically take screenshots during execution. You need to type cast WebDriver instance to TakesScreenshot.

Taking Screenshot in Selenium is just 3 Step process:

Step 1: Convert web driver object to TakesScreenshot
TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
Step 2: Call getScreenshotAs method to create image file
File source = takesScreenshot.getScreenshotAs(OutputType.FILE);
Step 3: Copy file to Desired Location
Example: In this example we will take screen capture of & save it as D:\Workspace_Eclipse\ScreehShotDemo\ScreenShot

Please refer below example

Utility Class where we kept screenShot method
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class TakeScreenShot {
 public static void screenShot(WebDriver driver, String filename) {
  TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
  File source = takesScreenshot.getScreenshotAs(OutputType.FILE);
  try {
   FileUtils.copyFile(source, new File(System.getProperty("user.dir")+"\\ScreenShot\\"+filename+".png"));
  } catch (Exception e) {
   // TODO Auto-generated catch block

Test Class where we have created few test cases and called screenShot method to take the screen shots :
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.utility.TakeScreenShot;

public class ScreenShotTest {
 WebDriver driver;

 public void setup() {
  driver = new ChromeDriver();
 public void testCase1() {
  driver.findElement("q")).sendKeys("ScreenShot Demo");
                TakeScreenShot.screenShot(driver, "testCase1");
} @Test public void testCase2() { Assert.assertTrue(true);
                TakeScreenShot.screenShot(driver, "testCase2");
 public void tearDown() {

POM.xml file given below:
<project xmlns=""

Please refer below YouTube video for more details:

No comments:

Post a Comment