关于 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

这哥们是利用PageFactory模式把驱动的创建做了封装,感兴趣可以了解一下。

搬运完了,准备过年。新年快了~!!!

在Python中实现PageFactory模式的更多相关文章

  1. 转在Python中实现PageFactory模式

    转自: http://www.cnblogs.com/fnng/p/5092383.html 关于 PageFactory 的概念主要是Java中内置了PageFactory类. import org ...

  2. Python中的Bunch模式

    引用: 当树这样的数据结构被原型化(或者乃至于被定型)时,它往往会时一个非常有用而灵活的类型,允许我们在其构造器中设置任何属性.在这些情况下,我们会需要用到一种叫做“Bunch”的设计模式. clas ...

  3. Python 中的设计模式详解之:策略模式

    虽然设计模式与语言无关,但这并不意味着每一个模式都能在每一门语言中使用.<设计模式:可复用面向对象软件的基础>一书中有 23 个模式,其中有 16 个在动态语言中“不见了,或者简化了”. ...

  4. Python中open文件的各种打开模式

    对于Python打开文件的模式,总是记不住,这次在博客里记录一下 r+: Open for reading and writing.  The stream is positioned  at  th ...

  5. python中文件操作的六种模式及对文件某一行进行修改的方法

    一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...

  6. 简介Python设计模式中的代理模式与模板方法模式编程

    简介Python设计模式中的代理模式与模板方法模式编程 这篇文章主要介绍了Python设计模式中的代理模式与模板方法模式编程,文中举了两个简单的代码片段来说明,需要的朋友可以参考下 代理模式 Prox ...

  7. Python中关于txt的简单读写模式与操作

    Python中关于txt的简单读写操作 常用的集中读写模式: 1.r 打开只读文件,该文件必须存在. 2.r+ 打开可读写的文件,该文件必须存在. 3.w 打开只写文件,若文件存在则文件长度清为0,即 ...

  8. python中各种文件打开模式

    在python中,总的来说有三种大的模式打开文件,分别是:a, w, r 当以a模式打开时,只能写文件,而且是在文件末尾添加内容. 当以a+模式打开时,可以写文件,也可读文件,可是在读文件的时候,会发 ...

  9. python2.7高级编程 笔记二(Python中的描述符)

    Python中包含了许多内建的语言特性,它们使得代码简洁且易于理解.这些特性包括列表/集合/字典推导式,属性(property).以及装饰器(decorator).对于大部分特性来说,这些" ...

随机推荐

  1. 【C-数组】

    一.一维数组 ①.定义方式 类型说明符 数组名 [常量表达式]; 如:int array[10]; 注意: 1) 数组的类型实际上是指数组元素的类型.对于同一个数组,其所有元素的数据类型都是相同的. ...

  2. 学习Word2vec

    有感于最近接触到的一些关于深度学习的知识,遂打算找个东西来加深理解.首选的就是以前有过接触,且火爆程度非同一般的word2vec.严格来说,word2vec的三层模型还不能算是完整意义上的深度学习,本 ...

  3. Java 程序性能优化

    1. singleton延时初始化 class Singleton { private static Singleton _instance = null; public synchronized S ...

  4. dp跟px的互相转换

    一 获取手机屏幕的密度 1 获取屏幕的宽和高,然后根据 直角三角形的 a边的平方+b边的平方=c边的平方 得到另一条边的长:然后除以 ,屏幕的尺寸,就是 手机的密度destity 2 根据上下文获取c ...

  5. 软将工程课设day9

    UI设计demo2.0. 在昨日demo的基础上进行了优化. 撰写美工设计报告,个人报告

  6. MySql学习(MariaDb)

    资料 http://www.cnblogs.com/lyhabc/p/3691555.html http://www.cnblogs.com/lyhabc/p/3691555.html MariaDb ...

  7. Java对象表示方式2:XStream实现对对象的XML化

    上一篇文章讲到了使用Java原生的序列化的方式来表示一个对象.总结一下这种对象表示方式的优缺点: 1.纯粹的Java环境下这种方式可以很好地工作,因为它是Java自带的,也不需要第三方的Jar包的支持 ...

  8. MySQL--使用xtrabackup进行备份还原

    使用rpm包安装xtrabackup ## 安装依赖包 yum -y install perl perl-devel libaio libaio-devel perl-Time-HiRes perl- ...

  9. 使用CSS sprites减少HTTP请求

    sprites是鬼怪,小妖精,调皮鬼的意思,初听这个高端洋气的名字我被震慑住了,一步步掀开其面纱后发觉很简单的东西,作用却很大 神马是CSS 小妖精 CSS sprites是指把网页中很多小图片(很多 ...

  10. Visual Studio 2015速递(1)——C#6.0新特性怎么用

    系列文章 Visual Studio 2015速递(1)——C#6.0新特性怎么用 Visual Studio 2015速递(2)——提升效率和质量(VS2015核心竞争力) Visual Studi ...