
封裝Selenium基本操作,讓所有頁面操作一鍵調用,讓UI自動化架構脫離高成本、低效率時代,将用例的重用性貫徹到極緻,讓煩人的PO模型變得無所謂,讓一個測試小白都能編寫并實作自動化。
知識儲備前提:熟練python語言理論與實際運用,熟悉selenium庫與自動化測試環境配置。
browseroperator.py 浏覽器操作
webdriveroperator.py WEBd頁操作
分層設計:基礎目錄,浏覽器操作與WEB操作分開。
一、browseroperator.py 的代碼如下:1、初始化函數def __init__(self),初始化浏覽相關參數
2、初始化浏覽器方法def open_url(self, **kwargs),先判斷使用哪種浏覽器。
**kwargs是不定長參數,dict格式,參數隻需要傳 url='www.baidu.com' ,方法調用隻用 opr.open_url(url='www.baidu.com'),打開了浏覽器,他會傳回webdriver的句柄,調用處接收到全流程操作網站元素。
暫時還未封裝IE 、火狐,留給各位朋友們實作吧,讓我們一起學習
3、def close_browser(self, **kwargs)關閉浏覽器,齊活,一并封裝了
import os
import time
from selenium import webdriver
from common.getconf import Config
from common.getfiledir import BASEFACTORYDIR
class BrowserOperator(object):
def __init__(self):
self.conf = Config()
self.driver_path = os.path.join(BASEFACTORYDIR, 'chromedriver.exe')
def open_url(self, **kwargs):
"""
打開網頁
:param url:
:return: 傳回 webdriver
"""
try:
url = kwargs['locator']
except KeyError:
return False, '沒有URL參數'
try:
type = self.conf.get('base', 'browser_type') #從配置檔案裡取浏覽器的類型
if type == 'chrome':
#處理chrom彈出的info
# chrome_options = webdriver.ChromeOptions()
# #option.add_argument('disable-infobars')
# chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
# self.driver = webdriver.Chrome(options=chrome_options, executable_path=self.driver_path)
self.driver = webdriver.Chrome(executable_path=self.driver_path)
self.driver.maximize_window()
self.driver.get(url)
elif type == 'IE':
print('IE 浏覽器')
else:
print('火狐浏覽器')
except Exception as e:
return False, e
return True, self.driver
def close_browser(self, **kwargs):
"""
關閉浏覽器
:return:
"""
self.driver.quit()
return True, '關閉浏覽器成功'
二、webdriveroperator.py代碼如下 1、def __init__(self, driver:Chrome),初始化浏覽器傳回的deriver句柄,
2、内容不一 一 介紹了,實作了所有頁面的操作,定義成功與否判斷、日志傳回等細節。各位看官細細品嘗,細節都在代碼裡,每個方法注釋大體可以說明了這個方法意義,很容易看懂。
還有很多UI操作沒有搬運上來,留給各位朋友們去實作吧,讓我們一起學習
import os
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import Chrome
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from common.getfiledir import SCREENSHOTDIR
class WebdriverOperator(object):
def __init__(self, driver:Chrome):
self.driver = driver
def get_screenshot_as_file(self):
"""
截屏儲存
:return:傳回路徑
"""
pic_name = str.split(str(time.time()), '.')[0] + str.split(str(time.time()), '.')[1] + '.png'
screent_path = os.path.join(SCREENSHOTDIR, pic_name)
self.driver.get_screenshot_as_file(screent_path)
return screent_path
def gotosleep(self, **kwargs):
time.sleep(3)
return True, '等待成功'
def web_implicitly_wait(self, **kwargs):
"""
隐式等待
:return:
type 存時間
"""
try:
s = kwargs['time']
except KeyError:
s = 10
try:
self.driver.implicitly_wait(s)
except NoSuchElementException:
return False, '隐式等待 頁面元素未加載完成'
return True, '隐式等待 元素加載完成'
def web_element_wait(self, **kwargs):
"""
等待元素可見
:return:
"""
try:
type = kwargs['type']
locator = kwargs['locator']
except KeyError:
return False, '未傳需要等待元素的定位參數'
try:
s = kwargs['time']
except KeyError:
s = 30
try:
if type == 'id':
WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.ID, locator)))
elif type == 'name':
WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.NAME, locator)))
elif type == 'class':
WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.CLASS_NAME, locator)))
elif type == 'xpath':
WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.XPATH, locator)))
elif type == 'css':
WebDriverWait(self.driver, s, 0.5).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
else:
return False, '不能識别元素類型[' + type + ']'
except NoSuchElementException:
return False, '元素[' + locator + ']等待出現逾時'
return True, '元素[' + locator + ']等待出現成功'
def find_element(self, type, locator, index = 0):
"""
定位元素
:param type:
:param itor:
:param index:
:return:
"""
#isinstance(self.driver, selenium.webdriver.Chrome.)
type = str.lower(type)
try:
if type == 'id':
elem = self.driver.find_elements_by_id(locator)[index]
elif type == 'name':
elem = self.driver.find_elements_by_name(locator)[index]
elif type == 'class':
elem = self.driver.find_elements_by_class_name(locator)[index]
elif type == 'xpath':
elem = self.driver.find_elements_by_xpath(locator)[index]
elif type == 'css':
elem = self.driver.find_elements_by_css_selector(locator)[index]
else:
return False, '不能識别元素類型:[' + type + ']'
except Exception:
screenshot_path = self.get_screenshot_as_file()
return False, '擷取[' + type + ']元素[' + locator + ']失敗,已截圖[' + screenshot_path + '].'
return True, elem
def element_click(self, **kwargs):
"""
點選
:param kwargs:
:return:
"""
try:
type = kwargs['type']
locator = kwargs['locator']
except KeyError:
return False, '缺少傳參'
try:
index = kwargs['index']
except KeyError:
index = 0
_isOK, _strLOG = self.find_element(type, locator, index)
if not _isOK: #元素沒找到,傳回失敗結果
return _isOK, _strLOG
elem = _strLOG
try:
elem.click()
except Exception:
screenshot_path = self.get_screenshot_as_file()
return False, '元素['+ locator +']點選失敗,已截圖[' + screenshot_path + '].'
return True, '元素['+ locator +']點選成功'
def element_input(self, **kwargs):
"""
輸入
:param kwargs:
:return:
"""
try:
type = kwargs['type']
locator = kwargs['locator']
text = str(kwargs['input'])
except KeyError:
return False, '缺少傳參'
try:
index = kwargs['index']
except KeyError:
index = 0
_isOK, _strLOG = self.find_element(type, locator, index)
if not _isOK: # 元素沒找到,傳回失敗結果
return _isOK, _strLOG
elem = _strLOG
# if 'test' != elem.get_property('type'): #校驗元素是不是text輸入框
# screenshot_path = self.get_screenshot_as_file()
# return False, '元素['+ itor +']不是輸入框,輸入失敗,已截圖[' + screenshot_path + '].'
try:
elem.send_keys(text)
except Exception:
screenshot_path = self.get_screenshot_as_file()
return False, '元素['+ locator +']輸入['+ text +']失敗,已截圖[' + screenshot_path + '].'
return True, '元素['+ locator +']輸入['+ text +']成功'
結語:封裝了基礎類,還得實作一個工廠,實作統一一個入口執行所有自動化 點贊關注~~~