Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Screenshot of element after scrolling to the element with Selenium + Python?

I want to take a screenshot of an element from a website at Chrome. Before i take the screenshot, i scroll down to the element with following code:

element = self.browser.find_element_by_class_name("class_name")
print(game_table.location)
self.browser.execute_script("arguments[0].scrollIntoView();", element)

After this I wan't to take a screenshot of this element with help of PIL:

location = element.location
size = element.size
img = browser.get_screenshot_as_png()
img = Image.open(io.BytesIO(img))

left = location['x']
top = location['y']
right = left + size['width']
bottom = top + size['height']

cropBox = (left, top, right, bottom)

img = img.crop(cropBox)
img.save('screenshot.png')

element.location gives me the coordinates of the element. But a screenshot will be taken from the view only, so I need to subtract from y-location the height I scrolled down to get the position of the element in the view.

How I get the height I scrolled down? Or is there a better solution?

like image 890
micharaze Avatar asked Jan 17 '26 19:01

micharaze


2 Answers

Thanks to Florent B.'s comment!

I changed the line location = element.location to

location = element.location_once_scrolled_into_view
like image 64
micharaze Avatar answered Jan 19 '26 10:01

micharaze


I think you can use the getBoundingClientRect javascript function for this, not sure though. you can find the details documentation here.

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

like image 30
Gaurang Shah Avatar answered Jan 19 '26 08:01

Gaurang Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!