在写完上一篇“基于Selenium的Web自动化框架”(http://www.cnblogs.com/AlwinXu/p/5836709.html)之后一直没有时间重新审视该框架,正好趁着给同事分享的机会,重新分析了一下框架,发现了很多不足之处,所以才有了这篇增强版。

到底在框架的哪一部分做了增强呢?这次主要从设计模式的角度来简单介绍一下。

首先我们来看一下之前是如何书写页面模式中的类的:

BasePage:

class BasePage(object):
"""description of class""" #webdriver instance
def __init__(self, driver):
self.driver = driver

GoogleMainPage:

from BasePage import BasePage

from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys class GoogleMainPage(BasePage):
"""description of class"""
searchbox = (By.ID,'lst-ib') def inputSearchContent(self,searchContent):
searchBox = self.driver.find_element(*self.searchbox)
searchBox.send_keys(searchContent+Keys.RETURN)

重新审视之前的实现,我们可以发现在各个子类页面中,均需要引用相当的selenium类库(比如webdriver),并且需要用webdriver来定位页面元素,这就会造成各个子类页面与selenium类库有较多的集成,并且也是书写上的浪费。

现在来看一下做了结构调整的部分呈现:

BasePage:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys class BasePage(object):
"""description of class""" #webdriver instance
def __init__(self, browser='chrome'):
'''
initialize selenium webdriver, use chrome as default webdriver
''' if browser == "firefox" or browser == "ff":
driver = webdriver.Firefox()
elif browser == "chrome":
driver = webdriver.Chrome()
elif browser == "internet explorer" or browser == "ie":
driver = webdriver.Ie()
elif browser == "opera":
driver = webdriver.Opera()
elif browser == "phantomjs":
driver = webdriver.PhantomJS()
try:
self.driver = driver
except Exception:
raise NameError("Not found %s browser,You can enter 'ie', 'ff' or 'chrome'." % browser) def findElement(self,element):
'''
Find element element is a set with format (identifier type, value), e.g. ('id','username') Usage:
self.findElement(element)
'''
try:
type = element[0]
value = element[1]
if type == "id" or type == "ID" or type=="Id":
elem = self.driver.find_element_by_id(value) elif type == "name" or type == "NAME" or type=="Name":
elem = self.driver.find_element_by_name(value) elif type == "class" or type == "CLASS" or type=="Class":
elem = self.driver.find_element_by_class_name(value) elif type == "link_text" or type == "LINK_TEXT" or type=="Link_text":
elem = self.driver.find_element_by_link_text(value) elif type == "xpath" or type == "XPATH" or type=="Xpath":
elem = self.driver.find_element_by_xpath(value) elif type == "css" or type == "CSS" or type=="Css":
elem = self.driver.find_element_by_css_selector(value)
else:
raise NameError("Please correct the type in function parameter")
except Exception:
raise ValueError("No such element found"+ str(element))
return elem def findElements(self,element):
'''
Find elements element is a set with format (identifier type, value), e.g. ('id','username') Usage:
self.findElements(element)
'''
try:
type = element[0]
value = element[1]
if type == "id" or type == "ID" or type=="Id":
elem = self.driver.find_elements_by_id(value) elif type == "name" or type == "NAME" or type=="Name":
elem = self.driver.find_elements_by_name(value) elif type == "class" or type == "CLASS" or type=="Class":
elem = self.driver.find_elements_by_class_name(value) elif type == "link_text" or type == "LINK_TEXT" or type=="Link_text":
elem = self.driver.find_elements_by_link_text(value) elif type == "xpath" or type == "XPATH" or type=="Xpath":
elem = self.driver.find_elements_by_xpath(value) elif type == "css" or type == "CSS" or type=="Css":
elem = self.driver.find_elements_by_css_selector(value)
else:
raise NameError("Please correct the type in function parameter")
except Exception:
raise ValueError("No such element found"+ str(element))
return elem def open(self,url):
'''
Open web url Usage:
self.open(url)
'''
if url != "":
self.driver.get(url)
else:
raise ValueError("please provide a base url") def type(self,element,text):
'''
Operation input box. Usage:
self.type(element,text)
'''
element.send_keys(text) def enter(self,element):
'''
Keyboard: hit return Usage:
self.enter(element)
'''
element.send_keys(Keys.RETURN) def click(self,element):
'''
Click page element, like button, image, link, etc.
'''
element.click() def quit(self):
'''
Quit webdriver
'''
self.driver.quit() def getAttribute(self, element, attribute):
'''
Get element attribute '''
return element.get_attribute(attribute) def getText(self, element):
'''
Get text of a web element '''
return element.text def getTitle(self):
'''
Get window title
'''
return self.driver.title def getCurrentUrl(self):
'''
Get current url
'''
return self.driver.current_url def getScreenshot(self,targetpath):
'''
Get current screenshot and save it to target path
'''
self.driver.get_screenshot_as_file(targetpath) def maximizeWindow(self):
'''
Maximize current browser window
'''
self.driver.maximize_window() def back(self):
'''
Goes one step backward in the browser history.
'''
self.driver.back() def forward(self):
"""
Goes one step forward in the browser history.
"""
self.driver.forward() def getWindowSize(self):
"""
Gets the width and height of the current window.
"""
return self.driver.get_window_size() def refresh(self):
'''
Refresh current page
'''
self.driver.refresh()
self.driver.switch_to()

GoogleMainPage:

from BasePage import BasePage

class GoogleMainPage(BasePage):
"""description of class"""
searchbox = ('ID','lst-ib') def __init__(self, browser = 'chrome'):
super().__init__(browser) def inputSearchContent(self,searchContent):
searchBox = self.findElement(self.searchbox)
self.type(searchBox,searchContent)
self.enter(searchBox)

Test

所做的改变:

  • 将与Selenium类库相关的操作做二次封装,放在BasePage中,其他子类页面自动继承相应的操作方法(如findelement,click等等)
  • 封装了findelement方法,可以根据页面元素的(类型,值)进行查找,只需要调用一个方法findelement(s),而不需要针对不同的类型调用不同的find方法(fine_element_by_xxxx())
  • 子类页面不需要引用selenium的类库,书写更加简单易读
  • 测试用例中也不需要引用selenium的任何类库,简单易读

代码已更新到GitHub:https://github.com/AlvinXuCH/WebAutomaiton 欢迎提供改进意见

基于Selenium的Web自动化框架增强篇的更多相关文章

  1. 基于Selenium的web自动化框架

    转自 : https://www.cnblogs.com/AlwinXu/p/5836709.html 1 什么是selenium Selenium 是一个基于浏览器的自动化工具,它提供了一种跨平台. ...

  2. 【转】基于Selenium的web自动化框架(python)

    1 什么是selenium Selenium 是一个基于浏览器的自动化工具,它提供了一种跨平台.跨浏览器的端到端的web自动化解决方案.Selenium主要包括三部分:Selenium IDE.Sel ...

  3. 【Selenium07篇】python+selenium实现Web自动化:PO模型,PageObject模式!

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第七篇博 ...

  4. 【Selenium05篇】python+selenium实现Web自动化:读取ini配置文件,元素封装,代码封装,异常处理,兼容多浏览器执行

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第五篇博 ...

  5. 【Selenium06篇】python+selenium实现Web自动化:日志处理

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第六篇博 ...

  6. 【Selenium03篇】python+selenium实现Web自动化:元素三类等待,多窗口切换,警告框处理,下拉框选择

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第三篇博 ...

  7. 【Selenium04篇】python+selenium实现Web自动化:文件上传,Cookie操作,调用 JavaScript,窗口截图

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 这是python+selenium实现Web自动化第四篇博 ...

  8. Web自动化框架LazyUI使用手册(3)--单个xpath抓取插件详解(selenium元素抓取,有此插件,便再无所求!)

    概述 前面的一篇博文粗略介绍了基于lazyUI的第一个demo,本文将详细描述此工具的设计和使用. 元素获取插件:LazyUI Elements Extractor,作为Chrome插件,用于抓取页面 ...

  9. 【Selenium01篇】python+selenium实现Web自动化:搭建环境,Selenium原理,定位元素以及浏览器常规操作!

    一.前言 最近问我自动化的人确实有点多,个人突发奇想:想从0开始讲解python+selenium实现Web自动化测试,请关注博客持续更新! 二.话不多说,直接开干,开始搭建自动化测试环境 这里以前在 ...

随机推荐

  1. Mysql性能优化二:索引优化

    1 索引的类型 UNIQUE唯一索引 不可以出现相同的值,可以有NULL值. INDEX普通索引 允许出现相同的索引内容. PRIMARY KEY主键索引 不允许出现相同的值,且不能为NULL值,一个 ...

  2. python之参数解包

    # 参数解包:将整个list当做参数传给函数 list = [1, 2, 4] def add_fn(a, b, c): return a + b + c sum = add_fn(*list) pr ...

  3. matlab中输入x. 与x的区别

    参考:http://www.madio.net/thread-27742-1-1.html 点乘的话,是对应元素相乘. 没点的话,按照矩阵相乘法则进行,这就要求前一个矩阵的列数等于第二个矩阵的行数. ...

  4. ThinkPHP 框架出现安全隐患 ,导致网站被持续攻击一周

    导读 据 ZDNET 报道,有超过 45000 个中国网站由于使用 ThinkPHP 框架受到了攻击. 这些攻击针对的是使用 ThinkPHP 构建的网站,ThinkPHP 是一个中国的 PHP 框架 ...

  5. 好消息,Manjaro Linux 18 已正式发布!

    导读 Manjaro Linux 18 已正式发布!Xfce 版本仍然是旗舰,Manjaro 为其提供了优雅且领先的集成体验.这一版本搭载 Xfce 4.13. 这一版本主要专注于在桌面和窗口管理器上 ...

  6. MyBatis:一对多关联查询

    MyBatis从入门到放弃四:一对多关联查询 前言 上篇学习了一对一关联查询,这篇我们学习一对多关联查询.一对多关联查询关键点则依然是配置resultMap,在resultMap中配置collecti ...

  7. BZOJ1030[JSOI2007]文本生成器——AC自动机+DP

    题目描述 JSOI交给队员ZYX一个任务,编制一个称之为“文本生成器”的电脑软件:该软件的使用者是一些低幼人群,他们现在使用的是GW文本生成器v6版.该软件可以随机生成一些文章―――总是生成一篇长度固 ...

  8. Sql 标识列 增长1000

    Sql 标识列 增长1000 的解决办法: 1. Open "SQL Server Configuration Manager" 2. Click "SQL Server ...

  9. python成长之路七-函数的进阶

    1,python中,名称空间分三种: 全局命名空间 局部命名空间(临时命名空间) 内置名称空间 2,作用域(两种): 1,全局作用域  包含:全局名称空间   内置名称空间 2,局部作用域  包含:局 ...

  10. Tunnel Warfare HDU - 1540(线段树最长连续区间)

    题意: 一条线上的点,D x是破坏这个点,Q x是表示查询以x所在的最长的连续的点的个数,R是恢复上一次破坏的点.   解析: 线段树结点 设置一个  lq记录区间左端点开始的最大连续个数,  rq ...