selenium中页面截图和元素截图的方法

一、页面截图

  selenium中页面截图的方法比较简单,可以直接使用selenium自带的截图方式save_screenshot(‘filename’)。

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://xlrz.chdi.com.cn/wssq/")
driver.save_screenshot("login.png")

  注意:save_screenshot的文件后缀名只能是png。

  get_screenshot_as_flie("文件路径"),与save_screenshot(‘filename’)功能相似。不过get_screenshot_as_flie("文件路径")可以指定文件路径,而save_screenshot(‘filename’)是默认在项目目录下生成图片。

二、元素截图

  元素截图需要先安装第三方pillow库,安装命令是“pip install pillow”.代码中需要先导入Image模组。

  例如获取学历认证登录页面,【登录】按钮具体代码如下:

from selenium import webdriver
from PIL import Image

driver = webdriver.Chrome()
driver.get("http://xlrz.chdi.com.cn/wssq/")
#获取登录页面的截图
driver.save_screenshot('login.png')
#定位登录按钮
imgcode=driver.find_element_by_name("submit")
#loaction方法获取元素坐标值X,y,且以字典的方式返回
left=imgcode.location['x']
top=imgcode.location['y']
#size方法获取元素的高度和宽度,以字典方式返回
right=left+imgcode.size['width']
bottom=top+imgcode.size['height']
#打开登录页面的截图
im=Image.open("login.png")
#获取登录按钮截图
mg=im.crop((left,top,right,bottom))
#保存截图,命名未ann
mg.save('ann.png')

  

原文地址:https://www.cnblogs.com/sunjump/p/15029963.html