转在Python中实现PageFactory模式
转自: http://www.cnblogs.com/fnng/p/5092383.html
关于 PageFactory 的概念主要是Java中内置了PageFactory类。
import org.openqa.selenium.support.PageFactory; ……
例子,http://libin0019.iteye.com/blog/1260090
Python(Selenium)中没有这个类。 PageFactory 的概念和Page Object应该类似,属于一种设计模式。所以并不局限于语言及场景。于是,好奇,既然Java有,那Python也应该有类似的玩法。还真让我给找到了类似的实现。
原文在此:https://jeremykao.wordpress.com/2015/06/10/pagefactory-pattern-in-python/
于是,就借助谷歌翻译加代码运行,弄懂了这哥们想要利用PageFactory 模式实现个什么东西,为了便于你的理解,我这里搬运过来给下结论。
selenium in python中的元素定位是这样的:
find_element_by_id("kw")
find_element_by_xpath("//*[@id='kw']")
或者是这样的:
from selenium.webdriver.common.by import By find_element(By.ID,"kw")
find_element(By.XPATH,"//*[@id='kw']")
通过PageFactory 模式的实现可以把元素定位变成这样的:
from pageobject_support import callable_find_by as find_by find_by(id_="kw")
find_by(xpath="//*[@id='kw']")
别看小小的改动,它其实使代码更容易的阅读和理解。
核心实现就是pageobject_support.py文件:

__all__ = ['cacheable', 'callable_find_by', 'property_find_by'] def cacheable_decorator(lookup):
def func(self):
if not hasattr(self, '_elements_cache'):
self._elements_cache = {} # {callable_id: element(s)}
cache = self._elements_cache key = id(lookup)
if key not in cache:
cache[key] = lookup(self)
return cache[key] return func cacheable = cacheable_decorator _strategy_kwargs = ['id_', 'xpath', 'link_text', 'partial_link_text',
'name', 'tag_name', 'class_name', 'css_selector'] def _callable_find_by(how, using, multiple, cacheable, context, driver_attr, **kwargs):
def func(self):
# context - driver or a certain element
if context:
ctx = context() if callable(context) else context.__get__(self) # or property
else:
ctx = getattr(self, driver_attr) # 'how' AND 'using' take precedence over keyword arguments
if how and using:
lookup = ctx.find_elements if multiple else ctx.find_element
return lookup(how, using) if len(kwargs) != 1 or kwargs.keys()[0] not in _strategy_kwargs :
raise ValueError(
"If 'how' AND 'using' are not specified, one and only one of the following "
"valid keyword arguments should be provided: %s." % _strategy_kwargs) key = kwargs.keys()[0]; value = kwargs[key]
suffix = key[:-1] if key.endswith('_') else key # find_element(s)_by_xxx
prefix = 'find_elements_by' if multiple else 'find_element_by'
lookup = getattr(ctx, '%s_%s' % (prefix, suffix))
return lookup(value) return cacheable_decorator(func) if cacheable else func def callable_find_by(how=None, using=None, multiple=False, cacheable=False, context=None, driver_attr='_driver', **kwargs):
return _callable_find_by(how, using, multiple, cacheable, context, driver_attr, **kwargs) def property_find_by(how=None, using=None, multiple=False, cacheable=False, context=None, driver_attr='_driver', **kwargs):
return property(_callable_find_by(how, using, multiple, cacheable, context, driver_attr, **kwargs))

帖一下具体的例子:

from pageobject_support import callable_find_by as find_by
from selenium import webdriver class BaiduSearchPage(object): def __init__(self, driver):
self._driver = driver search_box = find_by(id_="kw")
search_button = find_by(id_='su') def search(self, keywords):
self.search_box().clear()
self.search_box().send_keys(keywords)
self.search_button().click() if __name__ == '__main__':
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
BaiduSearchPage(driver).search("selenium")
driver.close()

同样封装了8种定位方法:
- id_ (为避免与内置的关键字ID冲突,所以多了个下划线的后缀)
- name
- class_name
- css_selector
- tag_name
- xpath
- link_text
- partial_link_text
当然,这只是PageFactory 模式的一种表现形式而已。除此之外,我还找到了另外一个PageFactory模式的例子。
https://github.com/mattfair/SeleniumFactory-for-Python
转在Python中实现PageFactory模式的更多相关文章
- 在Python中实现PageFactory模式
关于 PageFactory 的概念主要是Java中内置了PageFactory类. import org.openqa.selenium.support.PageFactory; …… 例子,htt ...
- Python中的Bunch模式
引用: 当树这样的数据结构被原型化(或者乃至于被定型)时,它往往会时一个非常有用而灵活的类型,允许我们在其构造器中设置任何属性.在这些情况下,我们会需要用到一种叫做“Bunch”的设计模式. clas ...
- Python 中的设计模式详解之:策略模式
虽然设计模式与语言无关,但这并不意味着每一个模式都能在每一门语言中使用.<设计模式:可复用面向对象软件的基础>一书中有 23 个模式,其中有 16 个在动态语言中“不见了,或者简化了”. ...
- Python中open文件的各种打开模式
对于Python打开文件的模式,总是记不住,这次在博客里记录一下 r+: Open for reading and writing. The stream is positioned at th ...
- python中文件操作的六种模式及对文件某一行进行修改的方法
一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...
- 简介Python设计模式中的代理模式与模板方法模式编程
简介Python设计模式中的代理模式与模板方法模式编程 这篇文章主要介绍了Python设计模式中的代理模式与模板方法模式编程,文中举了两个简单的代码片段来说明,需要的朋友可以参考下 代理模式 Prox ...
- Python中关于txt的简单读写模式与操作
Python中关于txt的简单读写操作 常用的集中读写模式: 1.r 打开只读文件,该文件必须存在. 2.r+ 打开可读写的文件,该文件必须存在. 3.w 打开只写文件,若文件存在则文件长度清为0,即 ...
- python中各种文件打开模式
在python中,总的来说有三种大的模式打开文件,分别是:a, w, r 当以a模式打开时,只能写文件,而且是在文件末尾添加内容. 当以a+模式打开时,可以写文件,也可读文件,可是在读文件的时候,会发 ...
- python2.7高级编程 笔记二(Python中的描述符)
Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...
随机推荐
- 8VC Venture Cup 2016 - Final Round D. Preorder Test 二分 树形dp
Preorder Test 题目连接: http://www.codeforces.com/contest/627/problem/D Description For his computer sci ...
- Failed to Attach to Process ID Xcode 解决办法
方法1. go to the Product menu and find the Edit Scheme menu there. While in Edit Scheme window, select ...
- appium+python自动化47-首次打开app权限弹窗问题
前言 用真机运行appium代码,首次打开app有的手机会出现权限弹窗问题,一般这种弹窗都是在引导页前面或者引导页后面出现.权限弹窗上面的按钮都是固定的, 只需要定位到"始终允许" ...
- 关于使用Android新版Camera即Camera2的使用介绍 暨解决Camera.PreviewCallback和MediaRecorder无法同时进行
新的相机API也就是Camera2是在Android 5.0引进的.通常情况下,我们都是使用Android旧的相机API,纵然在Android Studio里老是提示已经废弃,但是只要都能用,也就没必 ...
- 《Go语言实战》笔记之协程同步 sync.WaitGroup
原文地址(欢迎互换友链): http://www.niu12.com/article/8 sync 包提供同步 goroutine 的功能 <p>文档介绍</p><cod ...
- 【文件监控】之一:理解 ReadDirectoryChangesW part1
理解 ReadDirectoryChangesW 原作者:Jim Beveridge 原文:http://qualapps.blogspot.com/2010/05/understanding-rea ...
- RenderMonkey 练习 第三天 【OpenGL renderToTexture】
渲染到纹理: 1. 新建一个OpenGL 空effect; 2. 添加渲染目标纹理, Add Texture-> Add Render Texture 3. 添加一个渲染pass 4. 将pas ...
- DX12
CD3DX12_DESCRIPTOR_RANGE1 的baseShaderRegister 用来指定 t0 t1 b0 b1...的index t0 srv b0 constant buffer u0 ...
- HDU4667(有错)
正规的做法是找切点.三角形三个顶点分别对圆作切线,然后求切点(2个).两圆之间也要求切点(4个). 扯淡了这就..麻烦的要命.. 下面是写了一半的代码.. void process_circle(po ...
- 转:Android 签名验证机制(相当不错,强烈推荐)
转: http://riusksk.blogbus.com/logs/272154406.html Android应用签名验证过程中,满足以下条件才能安装应用: 1.SHA-1(除META-INF目 ...