How to Take Screenshots in Python with Selenium and ChromeDriver

How to Take Screenshots in Python with Selenium and ChromeDriver

Using the steps below, you will be able to take screenshots from a list of URLs today using Python 3, Selenium and ChromeDriver.


Step 1: Install Python 3, Selenium and ChromeDriver

Required tools for this tutorial:

 

Step 2: Create the Script

The script below will loop through the list of provided urls and save a screenshot of the url in your current directory.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

# Provide a list of urls to create screenshots from
links = ['http://example1.com','http://example2.com']

# The Chrome and ChromeDriver Paths will vary based on your Operating System. 
# This example shows how to configure ChromeDriver for Mac
CHROME_PATH = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'

# Set the Browser Size
WINDOW_SIZE = "1200,1200"

# Configure Chrome Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH

driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                          options=chrome_options)

# Loop through the list of urls and save the screenshot
for link in links:
    driver.get(link)

    # sleep for 2 seconds to allow the page to fully load.
    time.sleep(2)

    # create a clean filename from the url
    str = link.split('://')[1]
    filename = str.replace('/','__')
    image = filename.replace('.','_') + ".png" 

    # save the screenshot
    driver.save_screenshot(image)

# Close Selenium
driver.close()

Need help or have questions? Let us know in the comments below.


Leave a Reply

Your email address will not be published. Required fields are marked *