Screenshot on Failure

Introduction

One of the most useful debugging techniques in Selenium automation is capturing a screenshot when a test fails.

Instead of manually reproducing the failure, Selenium can automatically save the browser’s current state whenever an assertion or exception occurs. These screenshots become extremely valuable for debugging failed test cases and are commonly attached to automation reports.

In this tutorial, you’ll learn how to capture screenshots automatically on test failure using Selenium with Python, along with practical examples, real-world scenarios, common mistakes, and best practices.


What is Screenshot on Failure?

A Screenshot on Failure is a screenshot that Selenium captures automatically whenever a test encounters an assertion failure or an unexpected exception.

Example:

Run Test

      │

      ▼

Assertion Passed?

   ┌───────────────┐
   │               │
 Yes              No
   │               │
   ▼               ▼

Continue      Capture Screenshot

                   │

                   ▼

             Save Screenshot

                   │

                   ▼

            Report Test Failure

This helps testers understand exactly what was displayed on the screen at the moment the failure occurred.


Why Capture Screenshots on Failure?

Automatic screenshots help you:

  • Debug failed test cases.

  • Capture unexpected UI behavior.

  • Improve automation reports.

  • Reduce investigation time.

  • Preserve evidence of failures.


How Selenium Captures Screenshots on Failure

A common approach is:

  1. Execute the test.

  2. Catch an assertion or exception.

  3. Capture a screenshot.

  4. Re-raise the exception so the test still fails.


Example

from pathlib import Path

from selenium import webdriver
from selenium.webdriver.common.by import By


# Topic: 36. Screenshots - Screenshot on Failure
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 36_examples/test_03_screenshot_on_failure.py
#
# A common pattern is to capture a screenshot inside an exception handler, then
# re-raise the failure so the test still fails correctly.


def test_screenshot_when_assertion_fails():
    driver = webdriver.Chrome()

    try:
        driver.get("https://the-internet.herokuapp.com/login")

        try:
            heading = driver.find_element(By.TAG_NAME, "h2").text
            assert heading == "Wrong Expected Heading"
        except AssertionError:
            screenshot_dir = Path("screenshots")
            screenshot_dir.mkdir(exist_ok=True)
            driver.save_screenshot(str(screenshot_dir / "failure.png"))
            raise
    finally:
        driver.quit()

Understanding the Code

Import Required Libraries

from pathlib import Path

from selenium import webdriver
from selenium.webdriver.common.by import By

These modules are used to:

  • Create folders.

  • Save screenshots.

  • Launch the browser.

  • Locate web elements.


Create a Chrome Browser Instance

driver = webdriver.Chrome()

Starts a new Chrome browser session.


Open the Practice Website

driver.get(
    "https://the-internet.herokuapp.com/login"
)

Navigates to the login page.


Perform the Verification

heading = driver.find_element(
    By.TAG_NAME,
    "h2"
).text

assert heading == "Wrong Expected Heading"

Retrieves the page heading and intentionally compares it with an incorrect value.

This causes an AssertionError, allowing us to demonstrate how screenshots are captured during failures.


Catch the Failure

except AssertionError:

When the assertion fails, execution moves to this block.

Instead of immediately ending the test, Selenium first captures a screenshot.


Create the Screenshot Folder

screenshot_dir = Path("screenshots")

screenshot_dir.mkdir(
    exist_ok=True
)

Creates a screenshots folder if it does not already exist.


Capture the Screenshot

driver.save_screenshot(
    str(
        screenshot_dir /
        "failure.png"
    )
)

Captures the current browser window and saves it as failure.png.

The screenshot represents the exact state of the browser when the test failed.


Re-raise the Exception

raise

Re-raises the original assertion error.

This is important because:

  • The screenshot is saved.

  • The test is still reported as failed.

Without raise, the failure would be hidden and the test might incorrectly appear to have passed.


Close the Browser

driver.quit()

Closes the browser and ends the WebDriver session.


Practical Example

Suppose an e-commerce website displays an incorrect product price.

The automation script:

  • Verifies the displayed price.

  • Captures a screenshot if the verification fails.

  • Saves the screenshot for debugging.


Automation Testing Example

Consider a login page.

The automation script:

  • Verifies the dashboard title after login.

  • If the title is incorrect, captures a screenshot.

  • Reports the failure with visual evidence.


Real-World Example

Screenshots on failure are commonly used in:

  • Regression testing

  • Continuous Integration (CI)

  • Test reporting

  • UI validation

  • Enterprise automation frameworks

  • Cross-browser testing

  • Production defect investigation

Frameworks such as PyTest, Allure, and Extent Reports often attach these screenshots automatically to failed test reports.


Advantages of Screenshot on Failure

  • Speeds up debugging.

  • Preserves evidence of failures.

  • Improves automation reports.

  • Helps reproduce defects.

  • Saves investigation time.


Common Mistakes Beginners Make

Forgetting to Capture the Screenshot Before Raising the Exception

Always save the screenshot before re-raising the exception.


Swallowing the Exception

Do not remove the raise statement.

Without it, the test may appear to pass even though it actually failed.


Saving Screenshots to a Missing Folder

Always create the destination folder before saving screenshots.


Capturing Screenshots for Successful Tests

Normally, screenshots are needed only when failures occur unless reporting requirements specify otherwise.


Best Practices

  • Capture screenshots only when tests fail.

  • Save screenshots with meaningful file names.

  • Create a dedicated screenshots folder.

  • Attach screenshots to test reports.

  • Always re-raise the original exception after saving the screenshot.


Conclusion

Capturing screenshots on failure is one of the most valuable debugging techniques in Selenium automation. By saving the browser’s state before reporting the failure, testers can quickly identify UI issues without rerunning the test. Nearly every professional automation framework includes screenshot-on-failure functionality because it greatly simplifies troubleshooting and improves test reporting.


Frequently Asked Questions (FAQs)

Why capture screenshots on failure?

They provide visual evidence of what the browser displayed when the test failed, making debugging much easier.


Which Selenium method captures a screenshot?

Use:

driver.save_screenshot(
    "failure.png"
)

Why is raise used after taking the screenshot?

It re-throws the original exception so the test is correctly marked as failed.


Can screenshots be attached to test reports?

Yes.

Frameworks such as PyTest, Allure, and Extent Reports commonly include screenshots in failed test reports.


Where is screenshot-on-failure commonly used?

It is widely used in regression testing, CI/CD pipelines, enterprise automation frameworks, UI testing, and defect reporting.


Key Takeaways

  • Capture screenshots automatically when a test fails.

  • Save the screenshot before re-raising the exception.

  • Use driver.save_screenshot() to capture the browser window.

  • Always create the destination folder before saving screenshots.

  • Re-raise the exception so the test is correctly reported as failed.

  • Screenshot-on-failure is a standard practice in professional Selenium automation frameworks.