0
0
Selenium Pythontesting~10 mins

Element-level screenshot in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, finds a specific element, takes a screenshot of only that element, and verifies the screenshot file is created successfully.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import os
import time

def test_element_screenshot():
    driver = webdriver.Chrome()
    try:
        driver.get('https://example.com')
        element = driver.find_element(By.TAG_NAME, 'h1')
        screenshot_path = 'element_screenshot.png'
        element.screenshot(screenshot_path)
        time.sleep(1)  # wait to ensure file is saved
        assert os.path.exists(screenshot_path), 'Screenshot file not found'
    finally:
        driver.quit()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open, ready to navigate-PASS
2Navigates to 'https://example.com'Browser displays the example.com homepage with visible <h1> element-PASS
3Finds the <h1> element by tag name<h1> element is located on the pageElement is found without exceptionPASS
4Takes screenshot of the <h1> element and saves as 'element_screenshot.png'Screenshot file is created in the test folderFile 'element_screenshot.png' exists on diskPASS
5Quits the browser and ends the testBrowser window is closed-PASS
Failure Scenario
Failing Condition: The <h1> element is not found on the page or screenshot file is not created
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify after taking the element screenshot?
AThat the whole page screenshot is taken
BThat the screenshot file exists on disk
CThat the browser title is correct
DThat the element is clickable
Key Result
Always verify that the screenshot file is actually created after calling element.screenshot() to ensure your test captures the element image correctly.