Capture Screenshot in Selenium

Profile picture for user arilio666

In this article, we will see how we can take screenshots in selenium. This is done by using the takeScreenshot offered by the selenium library.

Why ScreenShots?

  • This is done to reduce manual effort.
  • Captured screenshots during the test are handy.
  • Screenshots help monitor tests every time by time it gets executed.
  • Screenshots can also help when a test case fails and identify the wrongs.
  • When the GUI is not visible during headless test execution, screenshots are beneficial.
  • We can store it in our customized destination.

ScreenShot In Action:

  • To take screenshots, TakeScreenshot is used, which enables the selenium webdriver to capture and store.
  • It also comes with getScreenShotAs(), which captures screenshot and stores it in the desired location.
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
  • Webdriver object is converted into TakeScreenshot.
  • OutputType also accompanies them. File to create an image file.
FileUtils.copyFile(screenshot , new File("C:\\main\\image.png));
  • Using the file utils, we then pass the source and destination of the image to be stored.
package week4.day2;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Screenshot {
    public static void main(String[] args) throws Throwable {
        ChromeDriver driver = new ChromeDriver();
        File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenshot, new File("C:\\TestLeaf\\UsernameSC.png"));
        } catch (IOException e) {
  • Here we have taken a screenshot of the page after inputting the username.
  • Then stored, it in our specified location using fileutils.