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.
This test opens a webpage, finds a specific element, takes a screenshot of only that element, and verifies the screenshot file is created successfully.
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()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open, ready to navigate | — | PASS |
| 2 | Navigates to 'https://example.com' | Browser displays the example.com homepage with visible <h1> element | — | PASS |
| 3 | Finds the <h1> element by tag name | <h1> element is located on the page | Element is found without exception | PASS |
| 4 | Takes screenshot of the <h1> element and saves as 'element_screenshot.png' | Screenshot file is created in the test folder | File 'element_screenshot.png' exists on disk | PASS |
| 5 | Quits the browser and ends the test | Browser window is closed | — | PASS |
element.screenshot('file.png') method do in Selenium Python?element.screenshot() method captures only the visible part of the specific element, not the whole page.button and save it as 'button.png'?screenshot() method is called on the element object, here button.button.screenshot('button.png'). Other options use incorrect methods or call on driver.element = driver.find_element(By.ID, 'logo')
element.screenshot('logo.png')element = driver.find_element(By.CLASS_NAME, 'submit-btn') element.screenshot = 'submit.png'
element.screenshot, but screenshot is a method and must be called with parentheses.element.screenshot('submit.png'), not assignment.find_elements to get a list of all buttons by tag name 'button'.enumerate starting at 1 to create filenames like 'button1.png', 'button2.png'. Call btn.screenshot() on each element.Pass the test and this pattern moves unknown