使用 python selenium 对元素进行屏幕截图显示屏幕错误部分的图像

ash*_*ets 5 python selenium python-imaging-library

我正在尝试使用此问题答案中的代码来截取网页上特定元素的屏幕截图当我几天前测试它时,这最初是有效的,但现在它产生的区域始终位于目标元素的上方和左侧。

原始代码的输出对调试没有多大帮助,因此我将其更改为在该区域周围绘制一个矩形,而不是裁剪它。

例子:

from selenium import webdriver
from PIL import Image, ImageDraw
from io import BytesIO

browser = webdriver.Chrome()
browser.get('http://www.google.com')

logo = browser.find_element_by_id('hplogo') #id of 'Google' image

location = logo.location
size = logo.size

im = Image.open(BytesIO(browser.get_screenshot_as_png()))

draw = ImageDraw.Draw(im)
draw.rectangle(((location['x'], location['y']), (location['x'] + size['width'], location['y'] + size['height'])), outline='black')

im.show()
browser.quit()
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述

绘制的框似乎具有正确的长宽比,但位置和大小不正确。如果您能解释导致此问题的原因以及解决此问题的任何帮助,我将不胜感激。

ash*_*ets 4

在对链接问题的已接受答案的评论中指出了该问题:返回的图像大小browser.get_screenshot_as_png()与实际窗口大小不符。需要调整图像的大小,使图像的坐标与网页上的坐标相对应。

工作代码:

from selenium import webdriver
from PIL import Image, ImageDraw
from io import BytesIO

browser = webdriver.Chrome()
browser.get('http://www.google.com')

element = browser.find_element_by_id('hplogoy')
screen = browser.get_screenshot_as_png()

location = element.location
size = element.size

im = Image.open(BytesIO(screen)) # uses PIL library to open image in memory

screensize = (browser.execute_script("return document.body.clientWidth"), #Get size of the part of the screen visible in the screenshot
              browser.execute_script("return window.innerHeight"))
im = im.resize(screensize) #resize so coordinates in png correspond to coordinates on webpage

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

draw = ImageDraw.Draw(im)
draw.rectangle( ((left, top), (right, bottom)), outline='red')

browser.quit()
im.show()
Run Code Online (Sandbox Code Playgroud)