WebUI自動化中截圖的使用

前言

做UI自動化時,有時候可能因爲需要把某個步驟的界面顯示截圖保存,這裏我用到的是webdriver的截圖功能。

環境搭建

這裏說的UI自動化指的是 web的UI自動化,使用的是Python+Selenium+webdriver寫的,用Unittest框架來組織用例和腳本。具體環境搭建可以參考之前的環境搭建詳細文章:
https://blog.csdn.net/NoamaNelson/article/details/102971936

封裝截圖功能creenShot.py

driver:指的是使用哪個瀏覽器的驅動,我後邊使用的是Chrome

# coding=utf-8

import time
from selenium import webdriver

def sav_creenshot(driver):
    now=time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time())) # 截圖保存的文件名格式
    pic_path = "../creenshot/"+now+'_screen.png' # 截圖保存的路徑
    # print(pic_path)
    driver.save_screenshot(pic_path) # 調用Driver的截圖保存功能

示例test_baidu.py

寫一個百度搜索hello的實例,test_baidu.py

# coding=utf-8
from selenium import webdriver
import time
import unittest
import logging
from common.creenShot import sav_creenshot # 導入剛剛封裝的截圖方法

class Testbaidu(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome() # 指定瀏覽器驅動
        self.url = "https://www.baidu.com/" # URL地址
        self.driver.maximize_window()  # 最大化窗口
        self.driver.get(self.url) # 獲取訪問網址
        self.log = logging.getLogger()  # 記錄日誌

    def tearDown(self):
        self.driver.close() # 關閉瀏覽器

    def test_search(self):
        # 搜索框輸入“hello”
        self.log.info("輸入框輸入hello")
        self.driver.find_element_by_id("kw").send_keys("hello")
        self.driver.find_element_by_id("su").click()
        time.sleep(2)
        self.assertIn("hello", self.driver.page_source)
        self.log.info("搜索成功")

if __name__ == "__main__":
	unittest.main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章