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")

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

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

每天进步一点点,加油!

相关推荐
我送炭你添花7 小时前
Pelco KBD300A 模拟器:04+1.Python 打包详解:历史、发展与多种方式对比
python·测试工具·运维开发
chuntian_tester9 小时前
Qwen通义千问大模型
测试工具·aigc
少云清10 小时前
【接口测试】3_Postman _Postman断言
测试工具·postman
我一定会有钱11 小时前
pytest基础
python·测试工具·测试用例·pytest
西游音月11 小时前
(6)pytest+Selenium自动化测试-测试用例编写
selenium·测试用例·pytest
Wpa.wk13 小时前
自动化测试 - 文件上传 和 弹窗处理
开发语言·javascript·自动化测试·经验分享·爬虫·python·selenium
少云清13 小时前
【接口测试】4_Postman _全局变量和环境变量
测试工具·postman
卓码软件测评14 小时前
CMA/CNAS软件测评机构:【Gatling数据库性能关联测试JDBC连接和SQL执行时间监控】
数据库·sql·测试工具·性能优化·测试用例
mike041216 小时前
Eclipse+maven+selenium自动化测试用例入门
selenium·eclipse·maven
2501_924064111 天前
2025年接口错误自动分析工具对比与性能测试平台选型指南
测试工具·性能优化·数据可视化