Last active
July 3, 2024 12:26
-
-
Save WittmannF/b714d3ceb7b6a5cd50002f11fb5a4929 to your computer and use it in GitHub Desktop.
Function for taking a screenshot of an element using selenium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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