Selenium

How to Take Screenshot in Selenium WebDriver with Timestamp (Java) – Complete Tutorial

How to Take Screenshot in Selenium WebDriver with Timestamp (Java)

By Bhau Automation Lab • Selenium 4 Screenshot Tutorial

🎯 What You Will Learn

  • How to capture screenshot in Selenium WebDriver
  • What is TakesScreenshot interface
  • How to use getScreenshotAs() method
  • How to add timestamp in screenshot name
  • How to take screenshot when test case fails
  • Real-time automation framework use case
💡 In real automation frameworks, screenshots must be captured automatically when test cases fail.

📌 What is TakesScreenshot Interface?

Selenium WebDriver provides a TakesScreenshot interface to capture screenshots during test execution. Using getScreenshotAs() method we can capture the screenshot and store it in a file.

💻 Selenium Screenshot Example (Java)

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ScreenshotExample {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new ChromeDriver();
        driver.get("https://google.com");

        // Create timestamp
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        // Take Screenshot
        TakesScreenshot ts = (TakesScreenshot) driver;
        File source = ts.getScreenshotAs(OutputType.FILE);

        File destination = new File("./Screenshots/Screenshot_" + timestamp + ".png");
        FileUtils.copyFile(source, destination);

        System.out.println("Screenshot captured successfully!");

        driver.quit();
    }
}

📍 How Screenshot Works

  • Cast WebDriver to TakesScreenshot
  • Use getScreenshotAs(OutputType.FILE)
  • Create timestamp for unique filename
  • Save file using FileUtils

⚡ Screenshot When Test Case Fails (Framework Use)

In real-time automation projects, screenshots are captured inside:

  • @AfterMethod (TestNG)
  • ITestListener interface
  • Catch block of try-catch

❓ Interview Questions

Q: Which interface is used to take screenshot in Selenium?

A: TakesScreenshot interface.

Q: Which method is used to capture screenshot?

A: getScreenshotAs()

🎥 Watch Complete Video

👉 Watch on YouTube: Take Screenshot in Selenium WebDriver

🎓 Key Takeaways

  • TakesScreenshot interface is used for capturing screenshots
  • getScreenshotAs() captures screenshot
  • Timestamp prevents file overwrite
  • Must implement screenshot on test failure in framework
  • Very important for Selenium interviews

🚀 Created with ❤️ by Bhau Automation Lab

Back to All Articles