0
0
Selenium Pythontesting~5 mins

Element screenshot in Selenium Python

Choose your learning style9 modes available
Introduction

Taking a screenshot of a specific element helps you check if that part of a webpage looks right. It is useful to catch visual bugs or confirm changes.

You want to verify a button's appearance after a click.
You need to save an image of a form field to check its style.
You want to compare a logo's look across different browsers.
You need to document a specific error message shown on the page.
Syntax
Selenium Python
element.screenshot('filename.png')
The element must be found first using a locator like find_element.
The filename should include the .png extension to save as an image file.
Examples
This saves a screenshot of the button with ID 'submit' as 'submit_button.png'.
Selenium Python
button = driver.find_element(By.ID, 'submit')
button.screenshot('submit_button.png')
This captures the element with class 'site-logo' and saves it as 'logo.png'.
Selenium Python
logo = driver.find_element(By.CSS_SELECTOR, '.site-logo')
logo.screenshot('logo.png')
Sample Program

This script opens example.com, finds the main heading <h1>, and saves its screenshot as 'heading.png'. It prints if the screenshot was saved successfully (True/False).

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver
with webdriver.Chrome() as driver:
    driver.get('https://example.com')
    time.sleep(2)  # wait for page to load

    # Find element
    heading = driver.find_element(By.TAG_NAME, 'h1')

    # Take screenshot of the heading element
    success = heading.screenshot('heading.png')

    print(f'Screenshot saved: {success}')
OutputSuccess
Important Notes

Make sure the element is visible on the screen before taking a screenshot.

Use waits instead of fixed sleep for better reliability.

The screenshot method returns True if the file was saved successfully.

Summary

Element screenshot captures only one part of the page, not the whole screen.

Use element.screenshot('file.png') after locating the element.

It helps catch visual issues in specific page parts easily.