Test Overview
This test opens a webpage, finds a specific element by its ID, takes a screenshot of that element, and verifies the screenshot file is created successfully.
This test opens a webpage, finds a specific element by its ID, takes a screenshot of 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.ID, 'logo') screenshot_path = 'element_screenshot.png' element.screenshot(screenshot_path) time.sleep(1) # wait to ensure file is saved assert os.path.exists(screenshot_path), f"Screenshot file {screenshot_path} was not created." 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 | Browser navigates to 'https://example.com' | Example.com homepage is loaded in the browser | — | PASS |
| 3 | Find element with ID 'logo' using driver.find_element(By.ID, 'logo') | Element with ID 'logo' is located on the page | Element is found without exception | PASS |
| 4 | Take screenshot of the element and save as 'element_screenshot.png' | Screenshot file 'element_screenshot.png' is created in the test folder | Screenshot file exists on disk | PASS |
| 5 | Assert that screenshot file exists using os.path.exists | File system contains 'element_screenshot.png' | assert os.path.exists('element_screenshot.png') passes | PASS |
| 6 | Close browser and end test | Browser window is closed, test ends cleanly | — | PASS |
element.screenshot('file.png') method do in Selenium Python?element.screenshot() method captures an image of the specific element, not the whole page.driver.save_screenshot() captures the full page, but element.screenshot() targets only one element.button as 'button.png'?element.screenshot(filename).button, calling button.screenshot('button.png') is correct syntax.element = driver.find_element(By.ID, 'logo')
element.screenshot('logo.png')
print('Screenshot saved')element.screenshot('logo.png'), which saves the element's image.element = driver.find_element(By.CLASS_NAME, 'submit-btn') element.screenshot()
screenshot() method requires a filename argument to save the image.element.screenshot() saves the button's image exactly, making comparison easy and automated.Pass the test and this pattern moves unknown