python+selenium自动化测试——POM模式

 

目录结构

 

python+selenium自动化测试——POM模式_第1张图片

 

 

测试基类 BasePage


from selenium import webdriver
from time import sleep, time


#定义页面的基础类,所有的页面都需要继承这个基础类
class BasePage(object):

'''初始化基础类'''
def __init__(self,driver,url):
self.driver = driver
self.url = url

def open_brows(self,driver):
self.driver.get(self.url)
self.driver.maximize_window()

# 关闭浏览器
def quit(self):
self.driver.quit()

#定位元素
def locator_elements(self,*locator):
el = self.driver.find_element(*locator)

#封装元素定位方式
def locator_element(self, *locator):
by = locator[0]
value = locator[1]
element = None
print('selector',locator)
if by == 'id' or by == 'name' or by == 'class' or by == 'tag' or by == 'link' \
or by == 'plink' or by == 'css' or by == 'xpath':
if by == 'id':
element = self.driver.find_element_by_id(value)
elif by == 'name':
element = self.driver.find_element_by_name(value)
elif by == 'class':
element = self.driver.find_element_by_class_name(value)
elif by == 'tag':
element = self.driver.find_element_by_tag_name(value)
elif by == 'link':
element = self.driver.find_element_by_link_text(value)
elif by == 'plink':
element = self.driver.find_element_by_partial_link_text(value)

elif by == 'css':
element = self.driver.find_element_by_css_selector(value)
elif by == 'xpath':
element = self.driver.find_element_by_xpath(value)
else:
print('没有找到元素')
return element
else:
print('输入的元素定位方式错误')

#输入文本
def input_text(self,selector,value):
element = self.find_element(selector) #调用封装的元素定位方法
element.send_keys(value)
try:
print('输入的内容:%s' % value)
except BaseException:
print('error')
#点击元素
def click(self,selector):
element = self.find_element(selector)
element.click()

# 隐式等待
def wait(self,seconds):
self.driver.implicitly_wait(seconds)

# 强制等待
def sleep(self,seconds):
time.sleep(seconds)

#切换至新窗体
def switch_to_new_current(self):
handles = self.driver.window_handles
self.driver.switch_to.window(handles[1])

#关闭旧窗体
def close_old_current(self):
self.driver.close()

# 切换至旧窗体
def switch_to_old_current(self):
handles = self.driver.window_handles
self.driver.switch_to.window(handles[0])

#切换至新窗体,并关闭旧窗体
def switch_window(self):
handles = self.driver.window_handles
self.driver.close()

#获取元素文本内容进行断言校验
def assert_by_text(self,selector,text):
element_text = self.find_element(selector).text
if element_text == text:
print('bingo')
else:
print(element_text + 'VS' + text)
print('wrong')

#切换至Iframe窗体
def switch_to_iframe(self,selector,text):
self.driver.switch_to.frame(self.driver.find_element())

#切换回默认窗体
def switch_to_default(self):
self.driver.switch_to.default_content()

 

你可能感兴趣的:(python+selenium自动化测试——POM模式)