selenium无法截图web元素

2024-04-30 01:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我可以截图整个页面使用Firefox.get_截图('2.png'),但是当我使用段落.截图('1.png'),它总是引发此异常:

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

Tags: messagegetpngsessionselenium页面commonfirefox
2条回答

出现这个异常是因为如果没有第三方库或您自己的代码来处理这个问题,您无法仅对selenium中的一个元素进行截屏。见This stackoverflow post

它使用一个名为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

在Firefox驱动程序中没有实现web元素的屏幕截图。解决方法是从屏幕截图中裁剪目标元素:

import StringIO
from selenium import webdriver
from PIL import Image

driver = webdriver.Firefox()
driver.get('http://stackoverflow.com')

# get the logo element
element = driver.find_element_by_id('hlogo')

# crop to the logo from the screenshot
rect = element.rect
points = [rect['x'], rect['y'], rect['x'] + rect['width'], rect['y'] + rect['height']]
with Image.open(StringIO.StringIO(driver.get_screenshot_as_png())) as img :
    with img.crop(points) as imgsub :
        imgsub.save("c:\\temp\\logo.png", 'PNG')

相关问题 更多 >