Saving Images in Chrome with Selenium


Here’s how to save images in Chrome browser using Selenium. The API has element.screenshot_as_png() method but apparently it’s not implemented at the moment.

With some minor changes to this answer I can save a image via the browser:

from selenium import webdriver
from PIL import Image

#chrome_options = ...
#chrome = webdriver.Chrome(chrome_options=chrome_options)
#element = chrome.find_element_by_id('some_id')

def save_image(chrome, element, save_path):
  # in case the image isn't isn't in the view yet
  location = element.location_once_scrolled_into_view
  size = element.size

  # saves screenshot of entire page
  chrome.save_screenshot(save_path)
  # uses PIL library to open image in memory

  image = Image.open(save_path)
  left = location['x']
  top = location['y']
  right = location['x'] + size['width']
  bottom = location['y'] + size['height']
  # defines crop points
  image = image.crop((left, top, right, bottom)) 
  # saves new cropped image
  image.save(save_path, 'png') 

🙂