面向对象的特性:封装、继承、多态。在自动化中同样适用,Selenium自动化测试中有一个名字经常被说起PageObject(思想与面向对象的特性相同),经过PO模式能够大大提升测试用例的维护效率。python
##传统测试脚本的弊端web
PO的核心要素:设计模式
前面基础场景选取的是baidu搜索页面(baidu页面简单,不须要搭建测试环境)baidu.py浏览器
from selenium import webdriver from time import sleep driver = webdriver.Firefox() driver.get("http://www.baidu.com") driver.find_element_by_xpath("//input[@id='kw']").send_keys("Bela") driver.find_element_by_xpath("//input[@id='su']").click() sleep(5) driver.quit()
将上面的脚本放在baidu.py文件中。框架
经过对baidu.py脚本的分析,能够提取到:ide
===================================================学习
实际测试场景中,可能有多个测试场景,若是每一个测试场景都须要维护url、浏览器驱动、元素定位等,效率会很是低。测试
from selenium.webdriver.support.wait import WebDriverWait from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC class BasePage(object): """ BasePage封装全部页面都公用的方法,例如driver, Find_Element等 """ # 实例化BasePage类时,最早执行的就是__init__方法,该方法的入参,其实就是BasePage类的入参。 # __init__方法不能有返回值,只能返回None def __init__(self,selenium_driver,base_url): self.driver = selenium_driver self.base_url = base_url # self.pagetitle = pagetitle def on_page(self,pagetitle): return pagetitle in self.driver.title def _open(self,url): self.driver.get(url) self.driver.maximize_window() def open(self): self._open(self.base_url,self.pagetitle) def find_element(self,*loc): #*loc任意数量的位置参数(带单个星号参数) # return self.driver.find_element(*loc) try: WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc)) return self.driver.find_element(*loc) except: print("%s 页面未能找到 %s 元素"%(self,loc)) def script(self,src): self.driver.excute_script(src) def send_keys(self, loc, vaule, clear_first=True, click_first=True): try: loc = getattr(self, "_%s" % loc) # getattr至关于实现self.loc if click_first: self.find_element(*loc).click() if clear_first: self.find_element(*loc).clear() self.find_element(*loc).send_keys(vaule) except AttributeError: print("%s 页面中未能找到 %s 元素" % (self, loc))
BasePage.py提取完毕,其中设计了BasePage类,对一些webdriver的方法进行了二次封装。优化
baidu.py基于BasePage.py进行优化(充分体现PO的设计思想,封装、继承)ui
# 基本测试场景 # from selenium import webdriver # from time import sleep # # driver = webdriver.Firefox() # driver.get("http://www.baidu.com") # # driver.find_element_by_xpath("//input[@id='kw']").send_keys("Bela") #输入框 # driver.find_element_by_xpath("//input[@id='su']").click() #百度一下按钮 # # sleep(3) # driver.quit() # 优化后的测试场景 from selenium.webdriver.common.by import By from PODemo.BasePage import BasePage #假设baidu.py、BasePage.py均在PODemo.BasePage目录下 from selenium import webdriver class SearchPage(BasePage): # 定位元素 search_loc = (By.ID,"kw") btn_loc = (By.ID,"su") def open(self): self._open(self.base_url) def search_content(self,content): BaiduContent = self.find_element(*self.search_loc) BaiduContent.send_keys(content) def btn_click(self): BaiduBtn = self.find_element(*self.btn_loc) BaiduBtn.click()
推广下个人博客专栏,目前选定了一个主题《从零学Selenium自动化测试框架》,让咱们从代码撸起,一步步实现Web自动化测试框架
该专题会从零带你搭建一个可用的自动化测试框架(基于python+selenium)
前提:你要掌握了python与selenium基础哦。要不你看不懂的。