转自: 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模式的更多相关文章

  1. 在Python中实现PageFactory模式

    关于 PageFactory 的概念主要是Java中内置了PageFactory类. import org.openqa.selenium.support.PageFactory; …… 例子,htt ...

  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. Problem G: 零起点学算法106——首字母变大写

    #include<stdio.h> #include<string.h> int main(void) { ]; int i,k; while(gets(a)!=NULL) { ...

  2. [转][Navicat for MySQL系列]Navicat如何使用(二)

    上一篇经验已经建立了数据连接,这篇我介绍一下Navicat for MySQL的“增删改查”功能是如何操作的. 工具/原料 Navicat for MySQL 10.1.7 数据库操作(基本) 1 远 ...

  3. Linux下Apache、PHP、MySQL默认安装路径

    Apache: 如果采用RPM包安装,安装路径应在 /etc/httpd 目录下 Apache配置文件:/etc/httpd/conf/httpd.conf Apache模块路径:/usr/sbin/ ...

  4. jq:zclip复制

    实例: <script type="text/javascript" src="js/jquery.js"></script> < ...

  5. 微信自动抢红包android实现

    AccessibilityService-微信自动抢红包 2018年02月01日 16:09:06 阅读数:1757 在领导发红包的时候,看到有些同事在1s.2s抢到红包,为什么他们能够这么快?一定是 ...

  6. 【LaTeX】E喵的LaTeX新手入门教程(4)图表

    这里说的不是用LaTeX画图,而是插入已经画好的图片..想看画图可以把滚动条拉到底.前情回顾[LaTeX]E喵的LaTeX新手入门教程(1)准备篇 [LaTeX]E喵的LaTeX新手入门教程(2)基础 ...

  7. Android-ImageView的属性android:scaleType作用

    在网上查了好多资料,大致都雷同,大家都是互相抄袭的,看着很费劲,不好理解,自己总结一下,留着需要看的话来查找. 代码中的例子如下: <ImageView android:id="@+i ...

  8. Razor语法(五)

    约定:客户端代码称C域,服务器端代码称S域 0. 基本原则Razor模板默认是C域(与php.aspx相同)任何C域都可以内嵌S域行内S域不可内嵌C域,多行S域可内嵌任何C域@符号是关键符号,使用@从 ...

  9. ubuntu创建sudo 用户

    The sudo command provides a mechanism for granting administrator privileges, ordinarily only availab ...

  10. VP9 Video Codec

    http://www.webmproject.org/vp9/ WebM Repositories libvpx: VP8/VP9 Codec SDK   pull http://git.chromi ...