Selenium Screenshots

A failed test needs proof of what went wrong. A screenshot captures the exact page state at the moment of failure, saving time compared to reading error logs alone. Many test reports embed screenshots automatically next to failed steps.

Diagram: Screenshot Capture Flow

Test Step Fails
     |
     v
TakesScreenshot Interface
     |
     v
Capture Image As File
     |
     v
Save To Reports Folder

The TakesScreenshot Interface

WebDriver classes like ChromeDriver implement the TakesScreenshot interface, giving access to screenshot methods directly.

Capturing A Full Page Screenshot

TakesScreenshot ts = (TakesScreenshot) driver;
File srcFile = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("./screenshots/homepage.png"));

This captures the visible browser viewport as an image file and saves it to a chosen folder.

Capturing A Screenshot Of One Element

WebElement logo = driver.findElement(By.id("site-logo"));
File elementShot = logo.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(elementShot, new File("./screenshots/logo.png"));

This captures only the logo element rather than the entire page, useful for checking one specific UI piece.

Naming Screenshots With Timestamps

String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
FileUtils.copyFile(srcFile, new File("./screenshots/failure_" + timestamp + ".png"));

Adding a timestamp prevents new screenshots from overwriting older ones during repeated test runs.

Automatic Screenshots On Failure

Test frameworks like TestNG support listener classes that trigger automatically when a test fails. A screenshot method placed inside this listener captures the page every time an assertion breaks, without manual calls inside every test.

public void onTestFailure(ITestResult result) {
    TakesScreenshot ts = (TakesScreenshot) driver;
    File source = ts.getScreenshotAs(OutputType.FILE);
    try {
        FileUtils.copyFile(source, new File("./screenshots/" + result.getName() + ".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Screenshot Limitations

  • Screenshots capture only the visible viewport by default, not content that requires scrolling.
  • Screenshots taken during animations may show a mid-motion frame instead of the final state.
  • Headless browser screenshots still work correctly, even without a visible window.

Practical Example

A test verifies that a course price displays correctly on the checkout page. If the assertion fails because the price shows an unexpected value, the test automatically saves a screenshot named price_mismatch_20260702.png inside the reports folder, giving the QA team instant visual proof of the issue.

Leave a Comment

Your email address will not be published. Required fields are marked *