How to Take Screenshot in Selenium Python: Simple Guide
In Selenium Python, you can take a screenshot using the
save_screenshot() method on the WebDriver instance. This method saves the current browser window as an image file, for example: driver.save_screenshot('filename.png').Syntax
The basic syntax to take a screenshot in Selenium Python is:
driver.save_screenshot('path/filename.png'): Saves the screenshot to the specified file path.
Here, driver is your WebDriver object controlling the browser.
python
driver.save_screenshot('screenshot.png')Example
This example opens a website, takes a screenshot, and saves it as screenshot.png in the current folder.
python
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import time # Setup Chrome options options = Options() options.add_argument('--headless') # Run browser in headless mode (no GUI) # Setup Chrome driver service (adjust path to your chromedriver) service = Service(executable_path='chromedriver') # Create WebDriver instance with webdriver.Chrome(service=service, options=options) as driver: driver.get('https://www.example.com') time.sleep(2) # Wait for page to load success = driver.save_screenshot('screenshot.png') if success: print('Screenshot saved successfully.') else: print('Failed to save screenshot.')
Output
Screenshot saved successfully.
Common Pitfalls
- Incorrect file path: Make sure the folder exists and you have write permission.
- Timing issues: Taking a screenshot before the page fully loads may capture a blank or incomplete page. Use waits or sleep.
- Driver not initialized: Ensure the WebDriver is properly created before calling
save_screenshot().
python
from selenium import webdriver # Wrong: calling save_screenshot before driver is created # driver.save_screenshot('fail.png') # This will cause an error # Right: driver = webdriver.Chrome() driver.get('https://www.example.com') driver.save_screenshot('success.png') driver.quit()
Quick Reference
Remember these tips when taking screenshots in Selenium Python:
- Use
save_screenshot('filename.png')on your driver instance. - Ensure the page is fully loaded before capturing.
- Use absolute or relative paths carefully.
- Headless mode works fine for screenshots.
Key Takeaways
Use driver.save_screenshot('filename.png') to capture the current browser window.
Wait for the page to load fully before taking a screenshot to avoid blank images.
Ensure the file path is valid and writable to save the screenshot successfully.
Headless browser mode supports screenshot capture without opening a GUI.
Always initialize the WebDriver before calling screenshot methods.