python logo

Selenium take screenshot

Python hosting: Host, run, and code Python in the cloud!

Selenium is a web automation framework that can be used for automated testing, web scraping and anything you can do with a web browser. We can use Selenium to take automated screenshots of a webpage.

Related course:
Browser Automation with Python Selenium

Take screenshot Selenium

The way this works is that Python uses the selenium driver to open a module, then selenium will start the defined web browser and open the page url. It will then take a screenshot and save it to the local hard disk.

take screenshot using python code take screenshot using python code

We start a web driver (Chromium) and open the webpage

from selenium import webdriver

driver = webdriver.Chrome()

Then we call the method:


The screenshot will be saved in the same directory as the program: the program path.

The full code is shown below. Now because I’ve tested with the chromium browser, it contains the ChromeOptions as parameter.

from selenium import webdriver

options = webdriver.ChromeOptions()
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome(chrome_options=options)



Remember to call driver.close() otherwise the browser stays open after the program finishes.

So you could use a shorter version, if you use another web browser like

from selenium import webdriver
driver = webdriver.Chrome()

Download Selenium Examples

Take screenshot of html element

You can take a screenshot of a html element. The way this works is that you first take a screenshot of the whole page and then crop it to its html element size.

from selenium import webdriver
from PIL import Image

# take screenshot
driver = webdriver.Chrome();
element = driver.find_element_by_id("hplogo");
location = element.location;
size = element.size;

# crop image
x = location['x'];
y = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
im ='pageImage.png')
im = im.crop((int(x), int(y), int(width), int(height)))'element.png')


Download Selenium Examples


Leave a Reply: