python - 使用 python selenium 截取一个元素显示屏幕错误部分的图像

标签 python selenium python-imaging-library

我正在尝试使用 this question. 的答案中的代码截取网页上特定元素的屏幕截图这最初在我几天前测试时有效,但现在它产生的区域始终在目标元素的左上方。

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

例子:

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

结果: enter image description here

绘制的框似乎长宽比正确,但位置和大小不正确。对于导致此问题的原因的任何解释以及修复它的任何帮助,我将不胜感激。

最佳答案

链接问题的已接受答案的评论中指出了这个问题: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()

关于python - 使用 python selenium 截取一个元素显示屏幕错误部分的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51996121/

相关文章:

python - 当数据大小大于axis时,matplotlib如何决定显示什么

python - 试图从谷歌抓取图像

image-processing - 我应该使用哪些处理步骤来清洁线条图的照片?

python - 可调整大小的窗口命令 python-maya

java - 测试运行了两次并且没有关闭

java - 如何使用java执行selenium脚本/批处理

c# - 对 URL 的远程 WebDriver 服务器的 HTTP 请求 - Chrome

python - PIL 图片导入错误

python PIL 安装在共享主机上

python - django admin 内联多对多自定义字段