Capturing Screenshots

Introduction

When Selenium tests fail unexpectedly, understanding what happened at the exact moment of failure can often be challenging. Error messages alone may not always provide sufficient information to determine why an element could not be located, why an assertion failed, or why the application’s behavior differed from expectations.

One of the most valuable troubleshooting techniques in Selenium automation testing is capturing screenshots. Screenshots preserve the exact visual state of the browser during test execution and provide valuable context for debugging failures.

Capturing screenshots allows automation engineers to:

  • Verify the application’s current UI state.

  • Identify missing or hidden elements.

  • Debug synchronization issues.

  • Analyze failed assertions.

  • Preserve failure information for later investigation.

  • Improve reporting and troubleshooting capabilities.

In this tutorial, you will learn how Selenium captures screenshots, understand when screenshots should be used, explore practical examples, common mistakes, best practices, and frequently asked interview questions.


What are Selenium Screenshots?

A Selenium screenshot is an image of the browser window captured during test execution.

Instead of:

Test Fails
     │
     ▼
Only Error Message Available
     │
     ▼
Investigate Manually
     │
     ▼
Run the Test Again

we can capture a screenshot:

Test Executes
      │
      ▼
Capture Screenshot
      │
      ▼
Preserve Browser State
      │
      ▼
Analyze Failure Easily
      │
      ▼
Identify the Root Cause

Screenshots significantly simplify troubleshooting efforts in Selenium automation frameworks.


Why Should We Capture Screenshots?

Screenshots allow developers to:

  • Verify webpage rendering.

  • Preserve UI state.

  • Debug failed test cases.

  • Investigate synchronization problems.

  • Identify incorrect application behavior.

  • Improve reporting mechanisms.

Large automation frameworks frequently capture screenshots automatically whenever test failures occur.


Practical Example

The following example demonstrates how Selenium captures a screenshot and stores it inside a dedicated screenshots folder.

from pathlib import Path

from selenium import webdriver


# Topic: Capturing Screenshots
# Practice site:
# https://www.testmuai.com/selenium-playground/
# Run:
# pytest -s 64_examples/test_02_capturing_screenshots.py
#
# Capturing screenshots preserves the exact UI state during test execution and
# greatly simplifies troubleshooting automation failures.


def test_capturing_screenshots():

    driver = webdriver.Chrome()

    try:
        driver.get(
            "https://www.testmuai.com/"
            "selenium-playground/"
        )

        screenshots = Path(
            "screenshots"
        )

        screenshots.mkdir(
            exist_ok=True
        )

        screenshot_path = (
            screenshots /
            "troubleshoot_capture.png"
        )

        driver.save_screenshot(
            str(screenshot_path)
        )

        assert (
            screenshot_path.exists()
        )

    finally:
        driver.quit()

Output

Chrome browser launched successfully.

Website opened successfully.

Screenshot captured successfully.

Screenshot saved successfully.


screenshots
      │
      ▼
troubleshoot_capture.png


Assertions Passed.

Test Executed Successfully.

Note: The actual screenshot contents will vary depending on the webpage displayed during execution.


Understanding the Code

Import Required Modules

from pathlib import Path

from selenium import webdriver

Imports:

  • Selenium WebDriver.

  • Path handling utilities used for managing folders and files.


Launch Chrome Browser

driver = webdriver.Chrome()

Creates a new Chrome browser session.


Open the Website

driver.get(
    "https://www.testmuai.com/"
    "selenium-playground/"
)

Opens the Selenium Playground webpage.


Create the Screenshots Directory

screenshots = Path(
    "screenshots"
)

screenshots.mkdir(
    exist_ok=True
)

This creates the following folder automatically whenever it does not already exist.

Project Folder
      │
      ▼
screenshots

The parameter:

exist_ok=True

ensures that Selenium does not raise an exception if the folder already exists.


Create the Screenshot Path

screenshot_path = (
    screenshots /
    "troubleshoot_capture.png"
)

This creates the following file path:

screenshots
      │
      ▼
troubleshoot_capture.png

which will store the captured screenshot.


Capture the Screenshot

driver.save_screenshot(
    str(screenshot_path)
)

Selenium performs the following steps:

Browser Window
       │
       ▼
Capture Current UI State
       │
       ▼
Generate PNG File
       │
       ▼
Save the Screenshot
       │
       ▼
Store Inside screenshots Folder

The screenshot preserves:

  • Browser content.

  • Element visibility.

  • UI rendering.

  • Application state.


Verify the Screenshot

assert (
    screenshot_path.exists()
)

This assertion verifies that:

  • The screenshot file was created successfully.

  • Selenium saved the image correctly.


Close the Browser

driver.quit()

Closes all browser windows and properly ends the WebDriver session.


Running the Example

Execute the following command:

py -3 -m pytest -s ^
"64_examples/test_02_capturing_screenshots.py"

Run all troubleshooting examples together:

py -3 -m pytest -s ^
"61_examples/"

Note: The -s option displays console output generated during test execution.


Execution Flow

Launch Browser
       │
       ▼
Open Website
       │
       ▼
Create Screenshots Folder
       │
       ▼
Capture Screenshot
       │
       ▼
Save PNG File
       │
       ▼
Verify Screenshot Exists
       │
       ▼
Assertions Passed
       │
       ▼
Close Browser

Relationship with Troubleshooting Test Failures

This section also includes topics such as:

  • Python Logging.

  • Capturing Page Source.

  • Browser Console Logs.

  • Debugging Failed Test Cases.

The shared conftest.py file provided in this section automatically captures screenshots whenever a test fails.

Test Failure
      │
      ▼
PyTest Detects Failure
      │
      ▼
Capture Screenshot
      │
      ▼
Save PNG File
      │
      ▼
Capture Page Source
      │
      ▼
Store Failure Artifacts

For example, failed tests automatically generate:

screenshots
      │
      ├── failed_test.png
      │
      └── failed_test.html

Note: Automatic screenshot capture using conftest.py is covered separately under Debugging Failed Test Cases. The current example focuses only on manually capturing screenshots using save_screenshot().


Automation Testing Example

Screenshots are extremely useful when:

Element Not Found
        │
        ▼
Capture Screenshot
        │
        ▼
Verify the UI State
        │
        ▼
Identify Missing Element
        │
        ▼
Fix the Automation Script

Similarly, screenshots help investigate:

  • Failed assertions.

  • Hidden elements.

  • Browser rendering issues.

  • Synchronization problems.


Real-World Example

Large automation frameworks commonly capture screenshots for:

  • Failed test cases.

  • Regression failures.

  • CI/CD pipeline executions.

  • Reporting tools.

  • Assertion failures.

  • Unexpected browser behavior.

For example:

Automation Failure
        │
        ▼
Capture Screenshot
        │
        ▼
Store Failure Information
        │
        ▼
Generate Reports
        │
        ▼
Simplify Troubleshooting

Screenshots are often considered the most useful debugging artifact available during Selenium automation testing.


Common Mistakes Beginners Make

Forgetting to Create the Folder

Incorrect

driver.save_screenshot(
    "screenshots/image.png"
)

if the folder does not exist.


Better

Path(
    "screenshots"
).mkdir(
    exist_ok=True
)

Always ensure that the destination folder exists before capturing screenshots.


Capturing Screenshots Too Late

Avoid capturing screenshots only after:

Browser Closed
      │
      ▼
Screenshot Requested
      │
      ▼
Operation Fails

Always capture screenshots before:

driver.quit()

is executed.


Ignoring Failure Screenshots

Screenshots frequently reveal:

  • Incorrect webpages.

  • Missing elements.

  • UI rendering problems.

  • Unexpected application behavior.

Always review failure screenshots carefully during troubleshooting.


Best Practices

  • Capture screenshots whenever important failures occur.

  • Maintain dedicated screenshot directories.

  • Use meaningful screenshot names.

  • Capture screenshots before closing the browser.

  • Integrate screenshots with reporting mechanisms whenever appropriate.

  • Preserve screenshots for CI/CD executions whenever possible.

  • Combine screenshots with logging and page source capture for comprehensive troubleshooting.


Conclusion

Capturing screenshots is one of the most valuable troubleshooting techniques available in Selenium automation testing. Screenshots preserve the exact visual state of the application during execution and significantly simplify debugging efforts when automation failures occur.

Well-designed screenshot mechanisms improve framework maintainability, simplify failure analysis, and greatly enhance troubleshooting capabilities in real-world automation projects.

Mastering screenshot capture techniques is an essential Selenium automation and interview skill.


Frequently Asked Questions (FAQs)

What is save_screenshot() in Selenium?

save_screenshot() captures the current browser window and stores it as an image file.


Which file format is used for Selenium screenshots?

Screenshots are typically saved as:

PNG

files.


Can screenshots be captured automatically?

Yes.

Large automation frameworks commonly capture screenshots automatically whenever tests fail using PyTest fixtures and hooks.


Are screenshots useful for debugging failed tests?

Yes.

Screenshots are among the most valuable debugging artifacts because they preserve the application’s exact visual state during execution.


Should screenshots be combined with logging?

Yes.

Combining:

  • Logging.

  • Screenshots.

  • Page source capture.

  • Reporting tools.

provides significantly better troubleshooting capabilities.


Key Takeaways

  • Selenium screenshots preserve the exact UI state during test execution.

  • save_screenshot() greatly simplifies troubleshooting automation failures.

  • Screenshots are particularly useful for debugging synchronization and rendering issues.

  • Dedicated screenshot directories improve framework maintainability.

  • Automatic screenshot capture is commonly implemented in large automation frameworks.

  • Screenshots complement logging and page source capture mechanisms effectively.

  • Proper screenshot management substantially improves debugging capabilities.

  • Capturing Screenshots is an important Selenium automation and interview topic.