Last modified: Oct 22, 2024 By Alexander Williams

Python Selenium: Taking Screenshots

Taking screenshots is an essential feature in web testing with Selenium. Python Selenium makes it easy to capture screenshots of web pages and specific elements.

Why Take Screenshots in Selenium?

Screenshots are crucial for verifying the appearance of web pages during automated tests. They help detect issues such as broken layouts or missing elements.

Prerequisites

To take screenshots in Selenium, you must have Python and Selenium installed. If you haven't installed Selenium yet, follow our Installation and Setup of Selenium with Python guide.

Capturing Full Page Screenshots

To take a full-page screenshot, you can use the save_screenshot() method. This method captures the entire browser window.


from selenium import webdriver

# Initialize the driver
driver = webdriver.Chrome()

# Open a webpage
driver.get('https://example.com')

# Take a full-page screenshot
driver.save_screenshot('full_page.png')

# Close the driver
driver.quit()

The screenshot will be saved in the specified location as .png file. You can customize the file name and path as needed.

Capturing Element-Specific Screenshots

To capture screenshots of specific elements, you'll need to locate the element and use the screenshot() method.


from selenium import webdriver

# Initialize the driver
driver = webdriver.Chrome()

# Open a webpage
driver.get('https://example.com')

# Find the element
element = driver.find_element_by_id('example-id')

# Take a screenshot of the element
element.screenshot('element_screenshot.png')

# Close the driver
driver.quit()

In this example, only the specified element will be captured. You can use different methods to locate elements, such as XPath or ID. Learn more about Finding Elements by ID.

Common Issues When Taking Screenshots

Ensure that the web page is fully loaded before capturing screenshots to avoid incomplete images. Adding waits may resolve such issues.


from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Wait until the element is present
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "example-id"))
)

Learn more about handling waits in Selenium by exploring the official Selenium documentation.

Conclusion

Taking screenshots in Selenium is a straightforward process. Whether capturing a full page or specific elements, the save_screenshot() and screenshot() methods are essential tools for web testing.

For more tutorials on working with Selenium, check out our guides on Getting Element Attributes and Getting Text from Elements.