使用selenium / python获取相对于视口的元素位置

时间:2016-06-17 12:59:47

标签: python google-chrome selenium

我正在使用以下代码截取屏幕截图并裁剪我想要的元素。但是,由于Chrome仅截取视口的屏幕截图,因此顶部数字太大,因为它从页面顶部开始计算。有没有办法获取相对于视口的位置?

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')

1 个答案:

答案 0 :(得分:3)

我能够通过滚动到元素,稍微向上滚动(从标题下面退出)使其工作,然后获取滚动位置并从顶部数字中减去

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')