0
0
Selenium Pythontesting~5 mins

Element-level screenshot in Selenium Python

Choose your learning style9 modes available
Introduction

Taking a screenshot of a specific element helps you focus on just that part of the page. It makes it easier to check if that element looks right or works well.

You want to verify the appearance of a button after a click.
You need to capture only the logo image on a webpage for comparison.
You want to save a screenshot of an error message box to share with developers.
You want to check if a form field is displayed correctly on different devices.
Syntax
Selenium Python
element = driver.find_element(By.CSS_SELECTOR, "selector")
element.screenshot('filename.png')

The element.screenshot() method saves the screenshot of that element only.

Use a good locator (like CSS selector or XPath) to find the element precisely.

Examples
This saves a screenshot of the button with ID 'submit-btn'.
Selenium Python
button = driver.find_element(By.ID, "submit-btn")
button.screenshot('submit_button.png')
This captures only the logo image inside the element with class 'site-logo'.
Selenium Python
logo = driver.find_element(By.CSS_SELECTOR, ".site-logo img")
logo.screenshot('logo.png')
Sample Program

This script opens a webpage, finds the main heading <h1>, and saves a screenshot of just that heading element.

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

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open example page
driver.get('https://www.example.com')

# Wait for page to load
time.sleep(2)

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

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

print('Screenshot saved as heading_element.png')

driver.quit()
OutputSuccess
Important Notes

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

Element screenshots capture only the element's area, not the whole page.

Use explicit waits instead of time.sleep() for better reliability in real tests.

Summary

Element-level screenshots help focus on specific parts of a webpage.

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

Good locators and visible elements ensure accurate screenshots.