What is the best way to take screenshots of tests in Selenium 2?


We can take screenshots of tests in Selenium webdriver. Capturing a screenshot is one of the most essential steps in failure analysis of failed tests. It is a three way step process to take screenshots.

Firstly, we shall convert the webdriver object to the interface called the TakeScreenshot. Then we have to utilize the getScreenshotAs method to capture the image. The file format of the image to be captured is passed as parameter to that method.

Finally, the file where the image is captured is to be copied to a location with the FileUtils.copyFile method.

Syntax

File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(s, new File("Image.png"));

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;
import java.io.File;
public class ScreenshotImg{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      //capture screenshot
      File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(s, new File("Img.png"));
      driver.quit();
   }
}

Updated on: 01-Feb-2021

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements