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

SeleniumAutomation TestingTesting Tools

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.


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


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) {
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //capture screenshot
      File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(s, new File("Img.png"));
Published on 01-Feb-2021 16:55:40