1.关键字驱动类
'''
关键字驱动类
一般在常态化中,考虑封装各类操作行为,作为关键字驱动的核心底层结构
以工具类的形态,便于其他的类进行调用。
常用的操作行为:
1.访问url
2.创建driver对象
3.元素定位
4.三类等待
5.输入、点击
6.切换iframe和句柄
。。。。。。
封装的概念上,我们优先考虑自己用上的内容,进行封装。
Selenium本身类似于一家超级无敌大的商场,关键字驱动类类似于家用的工具箱,要往工具箱里添加我们需要的东西。
在调用工具箱实现自己的自动化时,如果发现工具少了,或者缺失了,可以及时到Selenium中进行补充。
'''
import SafeDriver
import time
from class23 import chrome_options
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
def open_browser(type_):
'''
getattr是python内置的四大函数之一,用于获取指定对象的成员或者函数
driver = getattr(webdriver,type_)()意思就是
if type == 'Chrome':
driver = webdriver.Chrome()
elif type = 'Edge':
driver = webdriver.Edge()
elif.....
因为反射本身是用来获取指定对象属性的。如果要获取的是函数,则需要在反射的后面加()
例如:getattr(webdriver,type_)表示获取webdriver的type_属性
getattr(webdriver,type_)()表示获取webdriver的type_函数
'''
try:
if type == 'Chrome':
driver = webdriver.Chrome(options = chrome_options.options())
else:
driver = getattr(webdriver,type_)()
except Exception as e:
driver = webdriver.Chrome()
return driver
class Keys:
def __init__(self,type_):
self.driver = open_browser(type_)
self.driver.implicitly_wait(5)
def open(self,url):
self.driver.get(url)
def locate(self,by,value):
return self.driver.find_element(by,value)
def input(self,by,value,txt):
self.locate(by,value).send_keys(txt)
def click(self,by,value):
self.locate(by,value).click()
def quit(self):
self.driver.quit()
def driver_wait(self,by,value):
return WebDriverWait(self.driver,10,0.5).until(lambda el:self.locate(by,value),message = '元素获取失败')
def sleep(self,time_):
time.sleep(time_)
def switch_handle(self,status = 1):
handles = self.driver.window_handles
if status == 1:
self.driver.close()
self.driver.switch_to.window(handles[1])
def assert_almost_equal(self,by,value,expected):
try:
reality = self.locate(by,value).text
assert expected in reality,'{0}不在{1}的范围内'.format(expected,reality)
return True
except:
return False
def assert_text(self,by,value,expected):
try:
reality = self.locate(by,value).text
assert expected == reality,'{0}与{1}不相等'.format(expected,reality)
except Exception as e:
print('断言失败:{}'.format(e))
def switch_frame(self,value,by=None):
if by is None:
self.driver.switch_to.frame(value)
else:
self.driver.switch_to.frame(self.locate(by,value))
def get_text(self,by,value):
return self.locate(by,value).text
if __name__ == '__main__':
key = Keys('谷歌')
key.open('http://www.baidu.com')
2.调用关键字驱动
'''
通过调用关键字驱动类来实现自动化测试效果
测试用例类:调用关键字驱动类,来实现测试的业务需求
'''
from class24.web_keys import Keys
key = Keys('Chrome')
key.open('http://39.98.138.157/shopxo/index.php?s=/index/user/logininfo.html')
key.input('name','accounts','sixiaoyou')
key.input('name','pwd','xxx')
key.click('xpath','//button[text()="登录"]')
key.sleep(5)
key.quit()