1、相关函数
-
driver.get_screenshot_as_base64() : 截屏保存为base64适用于HTML中嵌入的图片。比如,想把截图放到html测试报告里。
-
driver.get_screenshot_as_file(filename):截屏保存为一个文件,提供路径
-
driver.get_screenshot_as_png() :截屏保存为一个二进制数据,很少用到
2、示例
- 定位一个错误的id,在抛出的异常中截图
from selenium import webdriver
from time import sleep
import time
driver=webdriver.Chrome()
driver.get("https://www.baidu.com/")
try:
driver.find_element_by_css_selector("#kwwwwwww")#错误的id
except Exception as msg:
print(u"异常原因:%s"%msg)
nowTime=time.strftime("%Y%m%d%H%M%S")
#截图
t=driver.get_screenshot_as_file(r"G:\htmlTest\%s.png"%nowTime)
print(u"截图结果:%s"%t)
sleep(5)
driver.quit()
3、部分截图
3.1、PIL模块
- PIL模块只支持到Python 2.7
- Python3.0中可以使用Pillow
- Pillow是PIL的一个派生分支,如今已经发展成为比PIL本身更具活力的图像处理库。
pip3 install Pillow
安装Pillow- Pillow导入时依然用
from PIL import Image
3.2、截取验证码
from selenium import webdriver
from PIL import Image
from time import sleep
driver=webdriver.Chrome()
#打开163邮箱注册界面
driver.get("https://reg.mail.163.com/unireg/call.do?cmd=register.entrance")
file_path=r"G:\htmlTest\full.png"
driver.save_screenshot(file_path)
obj=Image.open(file_path)
#定位验证码
img=driver.find_element_by_css_selector("#vcodeImg")
location=img.location
print(location)
size=img.size
left=location['x']
top=location['y']
right=left+size['width']
bottom=top+size['height']
region=(left,top,right,bottom)
imageObj=obj.crop(region)
#查看截到的验证码图片
#imageObj.show()
#保存验证码图片
imageObj.save(r"G:\htmlTest\code.png")
driver.quit()
3.3、save_screenshot和get_screenshot_as_file的区别
- 未发现有什么区别