转在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).对于大部分特性来说,这些" ...
随机推荐
- [BZOJ4304]/[JZOJ3486]道路改建
题目大意: 给你一个有向图,你可以把其中某一条单向边改成双向边,使得图中最大的SCC最大. 问SCC最大能是多少,有哪些方案? 思路: 对原图缩点后就变成了一个DAG. 我们在DAG上DP,记录一下从 ...
- iOS 带箭头菜单选项弹窗LFPopupMenu
一.效果图 由于是模拟器缩得比较小,一些细线可能显示不出来,不是bug哈. 二.用法 LFPopupMenuItem *item1 = [LFPopupMenuItem createWithTitle ...
- IE主页被篡改为360导航终极处理办法
不得不吐槽360真他妈是流氓至极,在不被用户许可的情况下直接修改用户浏览器默认主页,还不容易找到修改的地方. 以IE为例:我们将其首页设置为百度https://www.baidu.com/,终极处理办 ...
- 基于TCP通信的客户端断线重连
转载:http://www.cnblogs.com/networkcomms/p/4304362.html 源码下载 在CS程序中,断线重连应该是一个常见的功能. 此处的断线重连主要指的是服务器端因为 ...
- gitHub 基础命令
设置开发人员信息 git config --global user.name "chen" git config --global user.email "xxxxx@q ...
- Netty游戏服务器之六服务端登录消息处理
客户端unity3d已经把消息发送到netty服务器上了,那么ServerHandler类的public void channelRead(ChannelHandlerContext ctx, Obj ...
- Bestreviewapp给iOS软件写评论赚钱
BestReviewApp 这是一个评论类的活动,网站上会提供App列表,在iTunes评论这些应用就能获得报酬.目前账号中的余额可通过PayPal或支付宝提取出来.BestReviewApp 开放的 ...
- JS isNaN()函数
1.作用 isNaN() 函数用于检查其参数是否是非数字值. 2.JS <script> document.write(isNaN(123)); document.write(isNaN( ...
- prometheus,alertmanager 报警配置详解
vim prometheus.yml global: scrape_interval: 15s external_labels: monitor: 'codelab-monitor' scrape_c ...
- SQL Server 更新 触发器
- 复制代码 代码如下: create trigger TR_MasterTable_Update on MasterTable after update as if update ([Type])- ...