页面对象模型Page Object Modal是一种脚本设计模型,将页面元素,业务操作分割,当实际页面发生变化的时候,只需要修改页面元素文件,业务操作不需要修改。
具体实现需要先写一个页面公共类,里面写公共的方法,比如把元素定位,元素操作等方法重新封装。之后所有页面类继承页面公共类,页面类中只写该页面需要定位的元素,并把对应元素的操作封装成一个个方法。最后测试类调用这些方法组成一个业务测试用例。
还是以百度搜索为例子
framework包下面放一些公共类
pageobject包下面放需要测试的页面类
testsuites包下面放对应页面的测试类
class BasePage(object): def __init__(self,driver): self.driver = driver def find_element(self,selector): by = selector[0] value = selector[1] element = None 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 send(self,selector,value): element=self.find_element(selector)#调用封装的定位元素方法 try: element.send_keys(value) print('输入的内容%s' % value) except BaseException: print('error') def click(self,selector): element = self.find_element(selector) element.click()
from framework.base_page import BasePage class baidu(BasePage): kw = ['id','kw']#定位搜索输入框 su = ['id','su']#搜索按钮 def kw_send(self,value):#搜索框输入内容 self.send(self.kw,value) def su_click(self):#点击搜索按钮 self.click(self.su)
from selenium import webdriver from pageobject.BaiduPage import baidu import unittest class BaiduSerch(unittest.TestCase): def test_baidu(self): dr = webdriver.Firefox() dr.get('https://www.baidu.com') bai = baidu(dr) bai.kw_send('selenium') bai.su_click() if __name__ =='__main__': unittest.main()
最后就是测试类的,这里使用了unittest单元测试框架。bai = baidu(dr)每个页面都需要把driver传进去。使用WebDriver有一个要注意的就是 脚本运行的时候要保持只有一个driver。