Element-level screenshot in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import os # Initialize the Chrome WebDriver with webdriver.Chrome() as driver: driver.get('https://example.com') try: # Wait up to 10 seconds for the element with id 'logo' to be visible logo_element = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, 'logo')) ) # Take screenshot of the element screenshot_path = os.path.join(os.getcwd(), 'logo_screenshot.png') logo_element.screenshot(screenshot_path) # Assert the screenshot file exists assert os.path.isfile(screenshot_path), f"Screenshot file not found at {screenshot_path}" except Exception as e: print(f"Test failed: {e}") raise
The script starts by importing necessary Selenium modules and os for file path handling.
It opens Chrome browser and navigates to https://example.com.
Using WebDriverWait with visibility_of_element_located, it waits up to 10 seconds for the element with id logo to appear and be visible. This avoids errors if the element loads slowly.
Once found, it calls screenshot() on the element to capture only that element's image, saving it as logo_screenshot.png in the current directory.
Then it asserts the screenshot file exists to confirm success.
The with block ensures the browser closes automatically after the test.
Exceptions are caught and printed to help debug if the element is missing or other errors occur.
Now add data-driven testing to take element screenshots from three different element IDs: 'logo', 'header', and 'footer'.