我正尝试使用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()
绘制的框似乎是正确的长宽比,但是位置和大小不正确。对于造成此问题的原因有任何解释,也有解决此问题的帮助。
答案 0 :(得分:0)
该问题在链接问题的可接受答案的注释中指出: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()