Python+selenium之截图图片并保存截取的图片

本文转载:http://blog.csdn.net/u011541946/article/details/70141488

http://www.cnblogs.com/timsheng/archive/2012/09/05/2672651.html

介绍如何利用Selenium的方法进行截图,在测试过程中,是有必要截图,特别是遇到错误的时候进行截图。在selenium for Python中主要有三个截图方法,我们挑选其中最常用的一种。

截图技能对于测试人员来说应该是较为重要的一个技能。

在自动化测试中,截图可以帮助我们直观的定位错误、记录测试步骤。

记得以前在给某跨国银行做自动化项目的时候,某银的PM要求我们自动化测试的每一步至少需要1个截图,以证明每个功能都被自动化测试给覆盖过,在这种情况下截图就成了证明自动化测试有效性的重要手段。

好的测试人员都会截得一手好图,就跟骨灰级宅男定会吟得一手好诗一般。

webdriver的截图功能十分强悍。以前在截图的时候,最麻烦的问题莫过于页面太长而只能截到一屏,屏幕以外需要移动滚动条才能看到的区域一般是截不到的。现在webdriver解决了这个问题,无论页面有多长,webdriver都能比较完美的截到完整的页面。

下面的代码演示了如何使用webdriver进行截图:

 1 # -*- coding: utf-8 -*-
 2 from selenium import webdriver
 3 import unittest
 4 import os,sys,time
 5 import HTMLTestReport
 6 
 7 #登录
 8 driver =webdriver.Firefox()
 9 
10 current_time = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
11 current_time1 = time.strftime("%Y-%m-%d", time.localtime(time.time()))
12 print(current_time )
13 print(current_time1 )
14 # 必须打印图片路径HTMLTestRunner才能捕获并且生成路径,image**\**.png 是获取路径的条件,必须这样的目录
15 #设置存储图片路径,测试结果图片可以按照每天进行区分
16 
17 
18 
19 #通过if进行断言判断
20 driver.get("https://baidu.com/")
21 #新创建路径“.”表示当前整个.py文件的路径所在的位置,“\”路径分割符,其中的一个是“”表示转义字符
22 pic_path = '.\result\image\' + current_time1+'\' + current_time +'.png'
23 print(pic_path)
24 time.sleep(5)
25 print(driver.title)
26 #截取当前url页面的图片,并将截取的图片保存在指定的路径下面(pic_path),注:以下两种方法都可以
27 driver.save_screenshot(pic_path)
28 driver.save_screenshot('.\result\image\' + current_time1+'\' + current_time +'.png')  
29 
30 if u'百度一下,你就知道' == driver.title:
31     print ('Assertion test pass.') 
32 else:
33     print ('Assertion test fail.')
34 
35  #通过try抛出异常进行断言判断   
36 driver.get("https://baidu.com/")
37 driver.save_screenshot(pic_path)
38 try:
39     assert  u'百度一下,你就知道' ==  driver.title
40     print ('Assertion test pass.')  
41 except Exception as e:
42     print ('Assertion test fail.', format(e))
43 
44 time.sleep(5)
45 driver.quit()

save_screenshot方法实现了截图功能,只需要传入保存截图的文件名就可以了,十分方便。

原文地址:https://www.cnblogs.com/fengyiru6369/p/7234840.html