Element Screenshot

Introduction

The screenshot() method is one of Selenium’s most useful WebElement methods for capturing screenshots of individual web elements. Unlike browser-level screenshots that capture the entire webpage, WebElement.screenshot() captures only the specified element, making it particularly useful for UI validation, reporting, debugging, and visual regression testing.

Modern web applications contain numerous dynamic UI components such as login forms, buttons, images, error messages, and dashboards. Capturing screenshots of individual elements helps automation engineers identify UI issues quickly without including unnecessary portions of the webpage.

In this tutorial, you’ll learn what WebElement.screenshot() is, why it is used, its syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is Element Screenshot?

The screenshot() method captures an image of a specific web element and saves it to a file.

Unlike:

driver.save_screenshot()

which captures the entire webpage, the following statement captures only the required element:

element.screenshot()

For example, consider the following HTML:

<form id="login">

    <input id="username">

    <input id="password">

    <button>
        Login
    </button>

</form>

Selenium can capture only the Login form using:

login_form.screenshot(
    "login.png"
)

The screenshot() method is commonly used for capturing:

  • Login forms

  • Buttons

  • Images

  • Error messages

  • Success notifications

  • Tables

  • Charts

  • Dynamic UI components


Why Use Element Screenshot?

The screenshot() method is useful because it:

  • Captures only the required element.

  • Improves debugging capabilities.

  • Supports UI validation.

  • Helps identify visual issues quickly.

  • Produces readable automation scripts.

  • Is extensively used in professional automation frameworks.


Syntax

element.screenshot(
    "file_path"
)

Where:

  • element → Previously located WebElement.

  • "file_path" → Location where the screenshot will be saved.

  • screenshot() → Captures the element as an image file.


Example

The Selenium practice website contains a Login form. Selenium captures a screenshot of only the Login form and verifies that the image file is created successfully.

The Selenium code is:

from pathlib import Path

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


# Topic: 19. Element Size and Position - Element Screenshot
# Practice site: https://the-internet.herokuapp.com/login
# Run: pytest -s 19_examples/test_03_element_screenshot.py
#
# WebElement.screenshot() captures only the specified element, not the full page.


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

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

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

        screenshot_path = (
            screenshot_dir /
            "login_form_section19.png"
        )

        login_form = driver.find_element(
            By.ID,
            "login"
        )

        login_form.screenshot(
            str(screenshot_path)
        )

        assert screenshot_path.exists()

    finally:
        driver.quit()

Output

A screenshot containing
only the Login form is
saved successfully inside
the screenshots folder.

Example folder structure:

Project Folder
       │
       ▼
   screenshots
       │
       ▼
login_form_section19.png

Understanding the Code

Import the Required Modules

from pathlib import Path

from selenium.webdriver.common.by import By

Imports the required modules for creating directories and locating web elements.

Open the Login Page

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

Launches the Selenium practice website.

Create the Screenshot Directory

screenshot_dir = (
    Path("screenshots")
)

screenshot_dir.mkdir(
    exist_ok=True
)

Creates the screenshots folder if it does not already exist.

Create the Screenshot Path

screenshot_path = (
    screenshot_dir /
    "login_form_section19.png"
)

Specifies where the image file will be stored.

Locate the Login Form

driver.find_element(
    By.ID,
    "login"
)

Locates the Login form displayed on the webpage.

Capture the Screenshot

login_form.screenshot(
    str(screenshot_path)
)

Captures only the Login form and saves it as a PNG image.

Validate the Result

assert screenshot_path.exists()

Verifies that Selenium successfully created the screenshot file.


How Element Screenshot Works

            Python Script
                   │
                   ▼
            Locate Web Element
                   │
                   ▼
               screenshot()
                   │
                   ▼
          Capture Element Image
                   │
                   ▼
              Save PNG File
                   │
                   ▼
             Verify File Exists
                   │
                   ▼
             Perform Validation

Practical Example

Suppose you’re automating an E-Commerce website.

After placing an order successfully, the application displays:

Order Placed Successfully

Instead of capturing the entire webpage, Selenium can capture only the success message using:

success_message.screenshot(
    "success.png"
)

This significantly improves debugging during automation testing.


Automation Testing Example

Consider an online banking application.

Automation engineers frequently capture screenshots of:

  • Login forms.

  • Payment confirmations.

  • Error messages.

  • Profile information.

  • Transaction summaries.

  • Charts and graphs.

  • Dynamic dashboards.

  • UI components that fail during test execution.

Professional automation frameworks extensively use element screenshots while generating automated test reports.


Real-World Example

Automation engineers frequently use screenshot() while automating:

  • Banking applications.

  • E-Commerce websites.

  • Healthcare portals.

  • CRM systems.

  • ERP applications.

  • SaaS products.

  • Enterprise web applications.

  • Registration forms.

  • Dynamic dashboards.

Element-level screenshots are particularly useful when debugging UI failures during regression testing.


Advantages of Element Screenshot

  • Captures only the required element.

  • Improves debugging capabilities.

  • Supports UI validation.

  • Produces maintainable automation scripts.

  • Reduces unnecessary image content.

  • Extensively used in professional automation frameworks.


Element Screenshot vs Full Page Screenshot

FeatureElement ScreenshotFull Page Screenshot
Captures Entire PageNoYes
Captures Single ElementYesNo
Useful for UI ValidationYesYes
Useful for DebuggingYesYes
Produces Smaller ImagesYesNo
Professional Framework UsageExtensiveExtensive

Examples:

# Element Screenshot
element.screenshot(
    "element.png"
)
# Full Page Screenshot
driver.save_screenshot(
    "page.png"
)

Both approaches are frequently used together in professional automation frameworks.


Common Mistakes Beginners Make

Using Full Page Screenshots Unnecessarily

Avoid

driver.save_screenshot(
    "failure.png"
)

when only a single element needs to be validated.

Prefer

element.screenshot(
    "element.png"
)

whenever possible.

Element-level screenshots make debugging significantly easier.


Forgetting to Create the Screenshot Directory

Incorrect

element.screenshot(
    "screenshots/image.png"
)

when the folder does not exist.

Correct

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

Always create the required directories before saving screenshots.


Ignoring Dynamic Webpages

Modern applications frequently:

  • Render elements asynchronously.

  • Display messages dynamically.

  • Update dashboards continuously.

Always use appropriate synchronization techniques before capturing screenshots.


Best Practices

  • Capture screenshots only when necessary.

  • Prefer element-level screenshots for debugging UI issues.

  • Organize screenshots inside dedicated folders.

  • Use meaningful file names.

  • Apply synchronization techniques before capturing screenshots.

  • Include screenshots in automated test reports whenever appropriate.


Conclusion

The WebElement.screenshot() method provides a simple and reliable mechanism for capturing screenshots of individual web elements during Selenium automation testing. It plays an important role in UI validation, debugging, reporting, and visual regression testing across modern web applications.

Understanding how and when to use element screenshots correctly is essential for building scalable, reliable, and maintainable Selenium automation frameworks used in professional software testing environments.


Frequently Asked Questions (FAQs)

What is WebElement.screenshot() in Selenium?

The screenshot() method captures an image of a specific web element and saves it as a file.

What is the syntax of screenshot()?

element.screenshot(
    "file_path"
)

Which file format is commonly used?

PNG files are commonly used for Selenium screenshots.

What is the difference between element screenshots and full page screenshots?

  • element.screenshot() → Captures only the specified element.

  • driver.save_screenshot() → Captures the entire webpage.

When should I use element screenshots?

Use them when:

  • Debugging UI failures.

  • Validating visual components.

  • Generating automated reports.

  • Performing visual regression testing.


Key Takeaways

  • WebElement.screenshot() captures screenshots of individual web elements.

  • It is extensively used for debugging and UI validation.

  • Element screenshots are usually smaller and easier to analyze than full page screenshots.

  • Always organize screenshots using dedicated directories and meaningful file names.

  • Apply synchronization techniques when working with dynamically rendered webpages.

  • The screenshot() method is widely used in professional Selenium automation frameworks.