This article explains how to capture screenshots using Selenium WebDriver in Python. It includes screenshots of a specific web element and the entire webpage. The captured screenshots are saved in a specified directory on the local machine.
1. Create a Python file
- Import the necessary libraries
- Create an instance of the browser
- Navigate to the target URL
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize WebDriver
driver = webdriver.Chrome()
try:
# Open the webpage
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
2. Locate the web element and take a screenshot of that particular element
# Locate an element (ensure the ID is correct for your page)
element = driver.find_element(By.ID, "multi")
# Take a screenshot of the specific element
element.screenshot(r"C:\Users\Mausomi Paul\Downloads\element_screenshot.png")
print("Element screenshot saved successfully.")
Locates an element using its ID (“multi”). Ensure the ID is valid and corresponds to an existing element on the webpage and captures only the visual area of the selected element using the screenshot method and saves it as element_screenshot.png in the specified directory.
3. Capture and Save Full-Page Screenshot
# Take a full-page screenshot
file_path = r"C:\Users\Mausomi Paul\Downloads\full-page.png"
driver.save_screenshot(file_path)
print(f"Full-page screenshot saved successfully at: {file_path}")
Captures the entire visible webpage and saves it as full-page.png in the specified directory and prints confirmation messages to the console once the screenshots are saved.
4. Finally close the browser
finally:
# Close the browser
driver.quit()
Final code
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize WebDriver
driver = webdriver.Chrome()
try:
# Open the webpage
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
# Locate an element (ensure the ID is correct for your page)
element = driver.find_element(By.ID, "multi")
# Take a screenshot of the specific element
element.screenshot(r"C:\Users\Mausomi Paul\Downloads\element_screenshot.png")
print("Element screenshot saved successfully.")
# Take a full-page screenshot
file_path = r"C:\Users\Mausomi Paul\Downloads\full-page.png"
driver.save_screenshot(file_path)
print(f"Full-page screenshot saved successfully at: {file_path}")
finally:
# Close the browser
driver.quit()
Output
With this you have learned how selenium web driver takes care of screenshot.
Similar Posts
How to handles Drop down in selenium
How to Handle Alerts and Popups in Selenium
Locating Strategies in Selenium : Locating by Id
Installing Selenium and Configuring Web Driver
Selenium Python Example: How to run your first Test?