Selenium + Python 自动化测试08(截图)

我们的目标是:按照这一套资料学习下来,大家可以独立完成自动化测试的任务。

上一篇我们讨论了滑块的操作方法,本篇文章我们讲述一下截图的操作方法。希望能够帮到爱学的小伙伴。

在实际的测试项目组中我们经常要截屏保存报错信息,以便后续人工确认是否是真的bug。和对应的日志相对应。有时登录或者注册有图片上的验证码需要验证,也需要截图验证码,然后分析识别图片上的文字。

1、截屏的方法

页面截屏比较简单,可以使用selenium自带的方法:save_screenshot

下面以免费Swag Labs的网址(https://www.saucedemo.com/)为例进行说明:

练习代码如下:

复制代码
#打开浏览器,并最大化

driver.get("https://www.saucedemo.com/")   #打开练手的网站

driver.maximize_window()

time.sleep(3)

now =time.strftime("%Y-%m-%d %H_%M_%S")

pictures=now+".png"

driver.save_screenshot(pictures)

运行脚本以后可以看到产生对应的图片,在这个项目的文件夹下。

图片为了不重复命名,这里用了日期+时间的方法。

2、元素的截图

验证码如果要用图像识别的方式去处理的话,需要先对验证码元素进行截图。

如下例子:

前面是上一节滑块的内容,黄色是这次新增:

复制代码
driver.get("https://passport.ctrip.com/user/reg/home")

driver.maximize_window()

time.sleep(3)

# 点击同意并继续

driver.find_element_by_xpath("//*[@id='agr_pop']/div[3]/a[2]").click()

# 滑块的元素

slider =driver.find_element_by_css_selector("#slideCode > div.cpt-drop-box > div.cpt-drop-btn")

print(slider.size['width'])

print(slider.size['height'])

# 滑块区域的元素

slide_range =driver.find_element_by_css_selector("#slideCode > div.cpt-drop-box > div.cpt-bg-bar")

print(slide_range.size['width'])

print(slide_range.size['height'])



# 拖动滑块

ActionChains(driver).drag_and_drop_by_offset(slider, slide_range.size['width'], -slider.size['height']

                                             ).perform()

print("滑动成功")

time.sleep(3)

now =time.strftime("%Y-%m-%d %H_%M_%S")

pictures =now +".png"
复制代码
driver.save_screenshot(pictures)

# 元素的位置

captcha_image =driver.find_element_by_class_name("cpt-small-img")



# 获取元素的位置和大小

left =captcha_image.location['x']

top =captcha_image.location['y']

right =left +captcha_image.size["width"]

bottom =top+captcha_image.size["width"]

# 截取屏幕截图

im =Image.open(pictures)

im =im.crop((left,top,right,bottom))

im.save("captcha.png")

运行脚本查看文件夹下有对应的截图:

好了,今天就分享到这里。

每天进步一点点,加油!

相关推荐
newxtc5 小时前
【猿辅导-注册安全分析报告-无验证方式导致安全隐患】
开发语言·selenium·安全·yolo·安全爆破
gc_22995 小时前
学习Python中Selenium模块的基本用法(19:操作下拉框)
python·selenium
我的xiaodoujiao6 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 19--测试框架Pytest基础 3--前后置操作应用
python·学习·测试工具·pytest
程序员三藏17 小时前
Jmeter接口测试与压力测试
自动化测试·软件测试·python·测试工具·jmeter·接口测试·压力测试
一晌小贪欢19 小时前
Python爬虫第6课:Selenium自动化浏览器与动态内容抓取
爬虫·python·selenium·网络爬虫·python基础·python3·pathon爬虫
桃子不淘气20 小时前
2:测试平台之DB构建
测试工具
测试老哥1 天前
Postman环境变量设置全攻略
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
胜天半月子1 天前
接口测试 | 使用Postman实际场景化测试
测试工具·接口测试·postman
〆WangBenYan゜1 天前
postman 调用接口设置全局变量
测试工具·lua·postman