selenium 无法对网页元素进行屏幕截图

2023-11-29

enter image description here

我可以使用 Firefox.get_screenshot_as_file('2.png') 对整个页面进行屏幕截图,但是当我使用passage.screenshot('1.png') 对网页元素进行屏幕截图时,它总是会引发此异常:

selenium.common.exceptions.WebDriverException: Message: Unrecognized command: GET /session/284283fa-53fc-4b33-b329-e6e888dbdcb0/screenshot/{35834cf1-c9c7-4129-99b1-24f30c6b56e6}

您之所以会遇到此异常,是因为如果没有一些第三方库或您自己的代码来处理此问题,您就无法仅截取 selenium 中的一个元素的屏幕截图。看这个 stackoverflow 帖子

它使用一个名为 PIL 的库来完成此操作:

from selenium import webdriver
from PIL import Image

fox = webdriver.Firefox()
fox.get('https://stackoverflow.com/')

# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
fox.save_screenshot('screenshot.png') # saves screenshot of entire page
fox.quit()

im = Image.open('screenshot.png') # uses PIL library to open image in memory

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


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

selenium 无法对网页元素进行屏幕截图 的相关文章

随机推荐