Michael St Clair
Michael St Clair

Reputation: 6625

Get element location relative to viewport with selenium/python

I'm using the below code to take a screenshot and crop just the element I want. However, as Chrome only takes a screenshot of the viewport the top number is too large as it is counting from the top of the page. Is there a way to get the location relative to the viewport?

element = browser.find_element_by_xpath(locator)
browser.save_screenshot('screenshot.png')
location = element.location
size = element.size
im = Image.open('screenshot.png')           
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((int(left), int(top), int(right), int(bottom)))
im.save('screenshot2.png')

Upvotes: 3

Views: 3233

Answers (1)

Michael St Clair
Michael St Clair

Reputation: 6625

I was able to make it work by scrolling to the element, scroll slightly up (to get out from under the header), then get the scroll position and subtract it from the top number

element = browser.find_element_by_xpath(locator)
browser.execute_script("return arguments[0].scrollIntoView();", element)
browser.execute_script("window.scrollBy(0, -150);")
browser.save_screenshot('screenshot.png')
location = element.location
scroll = browser.execute_script("return window.scrollY;")
size = element.size
im = Image.open('screenshot.png')           
left = location['x']
top = location['y'] - scroll
right = location['x'] + size['width']
bottom = location['y'] + size['height'] - scroll
im = im.crop((int(left), int(top), int(right), int(bottom)))
im.save('screenshot2.png')

Upvotes: 8

Related Questions