selenium 提供了8中元素定位的方法(大家要学习元素的定位,首先可以学习下前端的基础知识,这样有利于我们学习自动化测试,大家可以看一下:http://www.runoob.com/)
下面我们创建一个类:
# coding = utf-8
import time
from selenium import webdriver
from selenium.webdriver.support.select import Select
class PySelenium(object):
def __init__(self, browser):
if browser == 'FireFox':
pydr = webdriver.Firefox()
elif browser == 'Chrome':
pydr = webdriver.Chrome()
elif browser == 'Ie':
pydr = webdriver.Ie()
else:
pydr = webdriver.Edge()
try:
self.driver = pydr
except Exception:
raise NameError("Not foud {} browser,You can enter 'Ie','Chrome','Firefox'.".format(browser))
之前我们见过,如果初始化webdriver的写法为
driver = webdriver.FireFox()
这里我们可以通过指定不同的浏览器driver来进行测试。这个类我们能得到相应浏览器的driver。
上文提到selenium有多中定位元素的方法,那么如果每定位一个元素就要写一次find_element_by_XXX,代码看起来是不是很冗余。那么我们来进行封装,实现根据定位方式来获取元素,代码如下:
def get_element(self, key):
'''根据类型获取元素值'''
dict = Properties("/Users/PycharmProjects/WebUI_Python/conf/element.properties").getValue(key)
locator_type = dict.split(">")[0]
locator_value = dict.split(">")[1]
if locator_type == 'id':
element = self.driver.find_element_by_id(locator_value)
elif locator_type == 'name':
element = self.driver.find_element_by_name(locator_value)
elif locator_type == 'tagName':
element = self.driver.find_element_by_tag_name(locator_value)
elif locator_type == 'linkText':
element = self.driver.find_element_by_link_text(locator_value)
elif locator_type == 'className':
element = self.driver.find_element_by_class_name(locator_value)
elif locator_type == 'cssSelector':
element = self.driver.find_element_by_css_selector(locator_value)
elif locator_type == 'xpath':
element = self.driver.find_element_by_xpath(locator_value)
else:
raise NameError("请输入正确的元素名称,例如:'id','name','className','tagName'.'linkText','cssSelector','xpath'")
return element
代码中dict值是我写的一个类,用来获取配置文件中的元素名、定位方式和定位值。代码如下:
# coding=utf-8
class Properties(object):
def __init__(self, fileName):
self.fileName = fileName
self.properties = {}
def __getDict(self, strName, dictName, value):
if (strName.find('.') > 0):
k = strName.split('.')[0]
dictName.setdefault(k, {})
return self.__getDict(strName[len(k) + 1:], dictName[k], value)
else:
dictName[strName] = value
return
def getProperties(self):
try:
pro_file = open(self.fileName, 'Ur')
for line in pro_file.readlines():
line = line.strip().replace('\n', '')
if line.find("#") != -1:
line = line[0:line.find('#')]
if line.find('=') > 0:
strs = line.split('=')
strs[1] = line[len(strs[0]) + 1:]
self.__getDict(strs[0].strip(), self.properties, strs[1].strip())
except Exception as e:
raise e
else:
pro_file.close()
return self.properties
def getValue(self, key):
dict = self.getProperties()
value = dict[key]
return value
配置文件如下:
#LoginPageElement
username = name>username
password = name>password
loginBtn = className>btn-success
userInfo = className>username
利用split(key).[]方法,分离配置文件中的数据。获取locator_type和locator_type
这种读取配置文件的方式,可以减少前端修改定位方式时我们维护脚本的工作量。
我在框架中加了一些日志,也是封装了一个日志类,以后再给大家贴代码。
下边是其他一些方法的封装:
def open_url(self, url):
'''打开网址'''
t1 = time.time()
try:
self.driver.get(url)
self.print_log("{0} Navigated to {1}, Spend {2} seconds".format(success, url, time.time() - t1))
except Exception:
self.print_log("{0} Unable to load {1}, Spend {2} seconds".format(fail, url, time.time() - t1))
raise
def quit(self):
'''退出浏览器'''
t1 = time.time()
self.driver.quit()
self.print_log("{0} Closed all window and quit the driver, Spend {1} seconds".format(success, time.time() - t1))
def max_window(self):
'''最大化窗口'''
t1 = time.time()
self.driver.maximize_window()
self.print_log("{0} Set browser window maximized, Spend {1} seconds".format(success, time.time() - t1))
def take_screenshot(self, file_path):
'''截图'''
t1 = time.time()
try:
self.driver.get_screenshot_as_file(file_path)
self.print_log("{0} Get the current window screenshot,path: {1}, Spend {2} seconds".format(success, file_path,time.time() - t1))
except Exception:
self.print_log("{0} Unable to get the current window screenshot,path: {1}, Spend {2} seconds".format(fail, file_path,time.time() - t1))
raise
def get_current_window_handle(self):
'''获取句柄'''
t1 = time.time()
handle = self.driver.current_window_handle
self.print_log("{0} Get current window handle, Spend {1} seconds".format(success, time.time() - t1))
return handle
def get_current_window_title(self):
'''获取页面的title'''
t1 = time.time()
title = self.driver.title
self.print_log("{0} Get current window title, Spend {1} seconds".format(success, time.time() - t1))
return title
def select(self,key1,key2):
'''按位置获取下拉框内容'''
t1 = time.time()
select = Select(self.get_element(key1))
try:
option = select.select_by_index(key2)
self.print_log("{0} Select element by index suscess, Spend {1} seconds".format(success, time.time() - t1))
return option
except Exception:
self.print_log("{0} selecting element by index failure, Spend {1} seconds".format(success, time.time() - t1))
raise
至此,我们得webdriver就封装好了,当然有很多其他的方法还没有封装,这里只是给大家一个思路,代码封装的好处。这样我们只要用到这些方法,调用我们封装好方法就可以了,而不用每次都要重写一遍。欢迎大家留言指正~