前言:
封装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 +']成功'
结语:封装了基础类,还得实现一个工厂,实现统一一个入口执行所有自动化,后续更新。
让我们一起学习。