In this Python Selenium article we want to learn How to Capture Screenshots with Python Selenium, Capturing screenshots during web automation can be a valuable tool for debugging, creating visual documentation or capturing evidence of specific web page states. Python Selenium provides easy methods to capture screenshots of web pages. in this tutorial, we want to talk about capturing screenshots with Python Selenium.
For working with the example of this tutorial you need some requirements, first you should have installed Python in your system, then we need to install Python Selenium and you can use pip for that like this.
1 |
pip install selenium |
Note: You can download the drivers from here.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
from selenium import webdriver from datetime import datetime # Launch the browser driver = webdriver.Chrome() # Open Google.com driver.get("https://www.google.com") # Capture a screenshot timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") filename = f"screenshot_{timestamp}.png" driver.save_screenshot(filename) # Close the browser driver.close() |
In the above code first, we have imported our required modules from Python Selenium.
1 2 |
from selenium import webdriver from datetime import datetime |
To begin capturing screenshots, we need to launch a browser instance using Selenium. Instantiate a webdriver object for the desired browser, in our case we are using Chrome browser.
1 |
driver = webdriver.Chrome() # Or webdriver.Firefox() for Firefox |
After that we need to navigate to the web page for which you want to capture a screenshot using the get() method of the webdriver object.
1 |
driver.get("https://www.google.com") |
To capture a screenshot, use the save_screenshot() method of the webdriver object and provide a filename for the screenshot. You can use a timestamp to ensure unique filenames for each screenshot.
1 2 3 |
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") filename = f"screenshot_{timestamp}.png" driver.save_screenshot(filename) |
After that you have captured the desired screenshots, remember to close the browser using the close() method.
1 |
driver.close() |
Learn More on Python Selenium
- Python Selenium Web Scraping
- Test Automation with Python Selenium
- Python Selenium WebDriver Tutorial
- Browser Interaction in Python Selenium
- Browser Profiles in Python Selenium
- Python Selenium Frames
Subscribe and Get Free Video Courses & Articles in your Email