硒不能截图Web元素 [英] selenium cannot screenshot a web element

查看:188
本文介绍了硒不能截图Web元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



使用一个名为PIL的库来执行它:

  from selenium import webdriver 
从PIL导入图像

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

#现在我们已经有了初步的东西了:D
element = fox.find_element_by_id('hlogo')#找到你想要的图片的部分
location =元素。位置
size = element.size
fox.save_screenshot('screenshot.png')#保存整个页面的截图
fox.quit()

im =图片.open('screenshot.png')#使用PIL库打开内存中的图像

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


im = im.crop((left,top,right,bottom))#定义裁剪点
im.save('screenshot.png')#保存新裁剪图像


I can screenshot a whole page using Firefox.get_screenshot_as_file('2.png'),but when I screenshot a web element using passage.screenshot('1.png'),it alway raise this exception:

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

解决方案

You're getting this exception because you cannot take a screenshot of just an element in selenium without some third-party libraries or your own code to handle this. See This stackoverflow post

Which uses a library called PIL to do it:

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

这篇关于硒不能截图Web元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆