logo

Selenium take screenshot

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 python.org.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://python.org')

Then we call the method:


driver.save_screenshot("screenshot.png")

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.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome(chrome_options=options)

driver.get('https://python.org')
driver.save_screenshot("screenshot.png")

driver.close()

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()
driver.get('https://pythonspot.com');
driver.save_screenshot("screenshot.png");

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();
driver.get('https://www.google.com');
element = driver.find_element_by_id("hplogo");
location = element.location;
size = element.size;
driver.save_screenshot("pageImage.png");

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

driver.quit()

Download Selenium Examples

BackNext

Leave a Reply

Login disabled