我正在尝试使用 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()
绘制的框似乎长宽比正确,但位置和大小不正确。对于导致此问题的原因的任何解释以及修复它的任何帮助,我将不胜感激。
最佳答案
链接问题的已接受答案的评论中指出了这个问题: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/