前言
在進行無人值守的UI自動化測試,如果頁面操作出現了問題,可以用截圖的方式保留問題現場,同時佐證自己發現的問題。下面將介紹3種截圖的方式:
driver.get_screenshot_as_file()
driver.save_screenshot()
Pillow包
前兩種是selenium自帶的api,最后一個需要單獨安裝第3方的包
測試代碼
1、get_screenshot_as_file():
import time
from datetime import datetime
from selenium import webdriver
import traceback
def currentDate():
'''生成當前日期字符串'''
date = time.localtime()
return '-'.join([str(date.tm_year), str(date.tm_mon),str(date.tm_mday)])
def currentTime():
'''生成當前時間字符串'''
date = time.localtime()
return '-'.join([str(date.tm_hour), str(date.tm_min),str(date.tm_sec)])
def createDir():
'''創建當前日期和當前時間目錄'''
path = os.path.dirname(os.path.abspath(__file__))
dateDir = os.path.join(path,currentDate())
#如果當前日期目錄不存的話就創建
if not os.path.exists(dateDir):
os.mkdir(dateDir)
timeDir= os.path.join(dateDir,currentTime())
#如果當前時間目錄不存的話就創建
if not os.path.exists(timeDir):
os.mkdir(timeDir)
return timeDir
def takeScreenshot(driver,savePath,pictureName):
picturePath = os.path.join(savePath, pictureName+'.png')
try:
driver.get_screenshot_as_file(picturePath)
except Exception as e:
print(traceback.print_exc())
# 獲取瀏覽器驅動實例
driver = webdriver.Chrome(executable_path='f:\\chromedriver')
#訪問搜狗首頁
driver.get('http://www.sogou.com')
time.sleep(3)
#搜狗首頁截圖
takeScreenshot(driver,createDir(),'sogou')
time.sleep(1)
#退出瀏覽器
driver.quit()
執行完成后在當前目錄下可以看到如下結果:
2、save_screenshot():
此方法和上一種是一樣的,只需要對takeScreenshot函數作如下修改即可:
def takeScreenshot(driver,savePath,pictureName):
picturePath = os.path.join(savePath, pictureName+'.png')
try:
#和get_screenshot_as_file方法類似
driver.save_screenshot(picturePath)
except Exception as e:
print(traceback.print_exc())
執行完成后在當前目錄下可以看到如下結果:
3、Pillow包:
需要先在命令行下安裝pillow包,命令如下:pip install Pillow,如果電腦中有多個python版本,而且想指定版本安裝的話參考之前的文章指定python版本pip安裝
執行完成后在當前目錄下可以看到如下結果:
注意
前兩種方式截的是瀏覽器的相關頁面,第3種是整個電腦桌面;
創建時間或日期目錄時%Y-%m-%d_%H:%M:%S這種是錯誤的格式,所有的包括 '' : / \ ? * < > | 這些特殊字符windows文件名無都無法使用,也無法保存,起名時需要注意,可以換成這種%Y-%m-%d_%H_%M_%S
————————————————
版權聲明:本文為CSDN博主「小小小小人ksh」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/kongsuhongbaby/article/details/87743133