0
0
Selenium Pythontesting~15 mins

Element screenshot in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Capture screenshot of a specific element on a webpage
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com'
Step 2: Locate the element with id 'logo' on the page
Step 3: Capture a screenshot of this element only
Step 4: Save the screenshot as 'logo_element.png' in the current directory
✅ Expected Result: A file named 'logo_element.png' is created containing the screenshot of the element with id 'logo'
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the element with id 'logo' is present before taking screenshot
Verify the screenshot file 'logo_element.png' is created after the test
Best Practices:
Use explicit waits to ensure the element is present and visible before interaction
Use By.ID locator for element identification
Handle exceptions if element is not found
Close the browser after test execution
Automated Solution
Selenium Python
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 WebDriver
with webdriver.Chrome() as driver:
    driver.get('https://example.com')

    # Wait for the element with id 'logo' to be visible
    wait = WebDriverWait(driver, 10)
    element = wait.until(EC.visibility_of_element_located((By.ID, 'logo')))

    # Take screenshot of the element
    screenshot_path = os.path.join(os.getcwd(), 'logo_element.png')
    element.screenshot(screenshot_path)

    # Assert the screenshot file exists
    assert os.path.isfile(screenshot_path), f"Screenshot file {screenshot_path} was not created"

This script uses Selenium WebDriver with Python to automate the task.

First, it opens the Chrome browser and navigates to 'https://example.com'.

It waits explicitly up to 10 seconds for the element with id 'logo' to be visible on the page, ensuring the element is ready for interaction.

Once found, it captures a screenshot of only that element and saves it as 'logo_element.png' in the current working directory.

Finally, it asserts that the screenshot file was created successfully.

The browser is automatically closed after the with block ends.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
Using a broad or incorrect locator like XPath without necessity
Not checking if the element exists before taking screenshot
Not closing the browser after test execution
Bonus Challenge

Now add data-driven testing to capture screenshots of elements with ids 'logo', 'header', and 'footer' saving each with the respective name.

Show Hint