Skip to content

Instantly share code, notes, and snippets.

@WittmannF
Last active August 22, 2022 04:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WittmannF/b714d3ceb7b6a5cd50002f11fb5a4929 to your computer and use it in GitHub Desktop.
Save WittmannF/b714d3ceb7b6a5cd50002f11fb5a4929 to your computer and use it in GitHub Desktop.
Function for taking a screenshot of an element using selenium
from selenium import webdriver
from PIL import Image
from io import BytesIO
def take_screenshot(element, driver, filename='screenshot.png'):
"""
Source: https://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python
"""
location = element.location_once_scrolled_into_view
size = element.size
png = driver.get_screenshot_as_png() # saves screenshot of entire page
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((left, top, right, bottom)) # defines crop points
im.save(filename) # saves new cropped image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment