Seleniium 是相当不错的一个第三方测试框架,可惜目前国内已经无法访问其官网(翻墙可以)。

不知道大家是否有认真查看过selenium 的api,我是有认真学习过的。selenium 的api中包含有WebDriverWait  和 expected_conditions这两个高级应用。

  下面先看WebDriverWait :

 import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method
IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method class WebDriverWait(object):
def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
"""Constructor, takes a WebDriver instance and timeout in seconds. :Args:
- driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote)
- timeout - Number of seconds before timing out
- poll_frequency - sleep interval between calls
By default, it is 0.5 second.
- ignored_exceptions - iterable structure of exception classes ignored during calls.
By default, it contains NoSuchElementException only. Example:
from selenium.webdriver.support.ui import WebDriverWait \n
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
"""
self._driver = driver
self._timeout = timeout
self._poll = poll_frequency
# avoid the divide by zero
if self._poll == 0:
self._poll = POLL_FREQUENCY
exceptions = list(IGNORED_EXCEPTIONS)
if ignored_exceptions is not None:
try:
exceptions.extend(iter(ignored_exceptions))
except TypeError: # ignored_exceptions is not iterable
exceptions.append(ignored_exceptions)
self._ignored_exceptions = tuple(exceptions) def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is not False."""
screen = None
stacktrace = None end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, 'screen', None)
stacktrace = getattr(exc, 'stacktrace', None)
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message, screen, stacktrace) def until_not(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value is False."""
end_time = time.time() + self._timeout
while True:
try:
value = method(self._driver)
if not value:
return value
except self._ignored_exceptions:
return True
time.sleep(self._poll)
if time.time() > end_time:
break
raise TimeoutException(message)

 哈哈,我始终相信贴出来总会有人看。WebDriverWait 类位于selenium.webdriver.support.ui下面的例子很简单,

Example:
 from selenium.webdriver.support.ui import WebDriverWait
element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId"))
is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).
until_not(lambda x: x.find_element_by_id("someId").is_displayed())
WebDriverWait 里面主要有两个方法,一个是until和until_not

那么我们可以这样用:
WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("某个按钮")).click()

意思就是在10秒内等待某个按钮被定位到,咱们再去点击。就是每隔0.5秒内调用一下until里面的表达式或者方法函数,要么10秒内表达式执行成功,要么10秒后抛出超时异常。

然后我们再看expected_conditions:
 from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import NoAlertPresentException """
* Canned "Expected Conditions" which are generally useful within webdriver
* tests.
"""
class title_is(object):
"""An expectation for checking the title of a page.
title is the expected title, which must be an exact match
returns True if the title matches, false otherwise."""
def __init__(self, title):
self.title = title def __call__(self, driver):
return self.title == driver.title class title_contains(object):
""" An expectation for checking that the title contains a case-sensitive
substring. title is the fragment of title expected
returns True when the title matches, False otherwise
"""
def __init__(self, title):
self.title = title def __call__(self, driver):
return self.title in driver.title class presence_of_element_located(object):
""" An expectation for checking that an element is present on the DOM
of a page. This does not necessarily mean that the element is visible.
locator - used to find the element
returns the WebElement once it is located
"""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
return _find_element(driver, self.locator) class visibility_of_element_located(object):
""" An expectation for checking that an element is present on the DOM of a
page and visible. Visibility means that the element is not only displayed
but also has a height and width that is greater than 0.
locator - used to find the element
returns the WebElement once it is located and visible
"""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
try:
return _element_if_visible(_find_element(driver, self.locator))
except StaleElementReferenceException:
return False class visibility_of(object):
""" An expectation for checking that an element, known to be present on the
DOM of a page, is visible. Visibility means that the element is not only
displayed but also has a height and width that is greater than 0.
element is the WebElement
returns the (same) WebElement once it is visible
"""
def __init__(self, element):
self.element = element def __call__(self, ignored):
return _element_if_visible(self.element) def _element_if_visible(element, visibility=True):
return element if element.is_displayed() == visibility else False class presence_of_all_elements_located(object):
""" An expectation for checking that there is at least one element present
on a web page.
locator is used to find the element
returns the list of WebElements once they are located
"""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
return _find_elements(driver, self.locator) class text_to_be_present_in_element(object):
""" An expectation for checking if the given text is present in the
specified element.
locator, text
"""
def __init__(self, locator, text_):
self.locator = locator
self.text = text_ def __call__(self, driver):
try :
element_text = _find_element(driver, self.locator).text
return self.text in element_text
except StaleElementReferenceException:
return False class text_to_be_present_in_element_value(object):
"""
An expectation for checking if the given text is present in the element's
locator, text
"""
def __init__(self, locator, text_):
self.locator = locator
self.text = text_ def __call__(self, driver):
try:
element_text = _find_element(driver,
self.locator).get_attribute("value")
if element_text:
return self.text in element_text
else:
return False
except StaleElementReferenceException:
return False class frame_to_be_available_and_switch_to_it(object):
""" An expectation for checking whether the given frame is available to
switch to. If the frame is available it switches the given driver to the
specified frame.
"""
def __init__(self, locator):
self.frame_locator = locator def __call__(self, driver):
try:
if isinstance(self.frame_locator, tuple):
driver.switch_to.frame(_find_element(driver,
self.frame_locator))
else:
driver.switch_to.frame(self.frame_locator)
return True
except NoSuchFrameException:
return False class invisibility_of_element_located(object):
""" An Expectation for checking that an element is either invisible or not
present on the DOM. locator used to find the element
"""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
try:
return _element_if_visible(_find_element(driver, self.locator), False)
except (NoSuchElementException, StaleElementReferenceException):
# In the case of NoSuchElement, returns true because the element is
# not present in DOM. The try block checks if the element is present
# but is invisible.
# In the case of StaleElementReference, returns true because stale
# element reference implies that element is no longer visible.
return True class element_to_be_clickable(object):
""" An Expectation for checking an element is visible and enabled such that
you can click it."""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
element = visibility_of_element_located(self.locator)(driver)
if element and element.is_enabled():
return element
else:
return False class staleness_of(object):
""" Wait until an element is no longer attached to the DOM.
element is the element to wait for.
returns False if the element is still attached to the DOM, true otherwise.
"""
def __init__(self, element):
self.element = element def __call__(self, ignored):
try:
# Calling any method forces a staleness check
self.element.is_enabled()
return False
except StaleElementReferenceException as expected:
return True class element_to_be_selected(object):
""" An expectation for checking the selection is selected.
element is WebElement object
"""
def __init__(self, element):
self.element = element def __call__(self, ignored):
return self.element.is_selected() class element_located_to_be_selected(object):
"""An expectation for the element to be located is selected.
locator is a tuple of (by, path)"""
def __init__(self, locator):
self.locator = locator def __call__(self, driver):
return _find_element(driver, self.locator).is_selected() class element_selection_state_to_be(object):
""" An expectation for checking if the given element is selected.
element is WebElement object
is_selected is a Boolean."
"""
def __init__(self, element, is_selected):
self.element = element
self.is_selected = is_selected def __call__(self, ignored):
return self.element.is_selected() == self.is_selected class element_located_selection_state_to_be(object):
""" An expectation to locate an element and check if the selection state
specified is in that state.
locator is a tuple of (by, path)
is_selected is a boolean
"""
def __init__(self, locator, is_selected):
self.locator = locator
self.is_selected = is_selected def __call__(self, driver):
try:
element = _find_element(driver, self.locator)
return element.is_selected() == self.is_selected
except StaleElementReferenceException:
return False class alert_is_present(object):
""" Expect an alert to be present."""
def __init__(self):
pass def __call__(self, driver):
try:
alert = driver.switch_to.alert
alert.text
return alert
except NoAlertPresentException:
return False def _find_element(driver, by):
"""Looks up an element. Logs and re-raises ``WebDriverException``
if thrown."""
try :
return driver.find_element(*by)
except NoSuchElementException as e:
raise e
except WebDriverException as e:
raise e def _find_elements(driver, by):
try :
return driver.find_elements(*by)
except WebDriverException as e:
raise e

哈哈,我相信这个py文件大家一看就能懂。这无非就是一些预期条件。

结合上面的WebDriverWait,我们可以这么用:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC '''
10秒钟等待浏览器弹出的对话框,如果出现,就点击确定按钮
'''
WebDriverWait(chromedriver,10).until(EC.alert_is_present()).accept()
我们的自动化脚本跑得快慢或者出现异常,很大程度上取决于我们设定的等待时间,如果你还是习惯于time.sleep(5)这种方式的话,这将会浪费很多时间。
根据expected_conditions.py文件的写法,我们也可以定义一些自己的期待类,例如:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC class must_get_url(object):
'''
必须到达的URL
参数:
url - 必须到达的地址
'''
def __init__(self, url):
self.url = url def __call__(self, driver):
driver.get(self.url)
return self.url == driver.current_url options = webdriver.ChromeOptions()
options.add_argument("--test-type")
chromedriver = webdriver.Chrome(r"E:\MyProject\WebDriver\chromedriver.exe",chrome_options=options)
WebDriverWait(chromedriver,10).until(must_get_url("https://www.baidu.com"))
												

Selenium 高阶应用之WebDriverWait 和 expected_conditions的更多相关文章

  1. Selenium 应用 WebDriverWait 和 expected_conditions(待验证)

    收藏在我的收藏看不到,只能copy了,转载至http://www.cnblogs.com/yicaifeitian/p/4749149.html 哈哈,我始终相信贴出来总会有人看.WebDriverW ...

  2. selenium (四) WebDriverWait 与 expected_conditions

    在介绍WebDriverWait之前,先说一下,在selenium中的两种等待页面加载的方式,第一种是隐式等待,在webdriver里面提供的implicitly_wait()方法,driver.im ...

  3. python入门16 递归函数 高阶函数

    递归函数:函数内部调用自身.(要注意跳出条件,否则会死循环) 高阶函数:函数的参数包含函数 递归函数 #coding:utf-8 #/usr/bin/python """ ...

  4. WebDriverWait与expected_conditions结合使用

    expected_conditions判断页面元素 demo2 from selenium import webdriver from selenium.webdriver.support.ui im ...

  5. c#语言-高阶函数

    介绍 如果说函数是程序中的基本模块,代码段,那高阶函数就是函数的高阶(级)版本,其基本定义如下: 函数自身接受一个或多个函数作为输入. 函数自身能输出一个函数,即函数生产函数. 满足其中一个条件就可以 ...

  6. swift 的高阶函数的使用代码

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  7. JavaScript高阶函数

    所谓高阶函数(higher-order function) 就是操作函数的函数,它接收一个或多个函数作为参数,并返回一个新函数. 下面的例子接收两个函数f()和g(),并返回一个新的函数用以计算f(g ...

  8. 分享录制的正则表达式入门、高阶以及使用 .NET 实现网络爬虫视频教程

    我发布的「正则表达式入门以及高阶教程」,欢迎学习. 课程简介 正则表达式是软件开发必须掌握的一门语言,掌握后才能很好地理解到它的威力: 课程采用概念和实验操作 4/6 分隔,帮助大家理解概念后再使用大 ...

  9. python--函数式编程 (高阶函数(map , reduce ,filter,sorted),匿名函数(lambda))

    1.1函数式编程 面向过程编程:我们通过把大段代码拆成函数,通过一层一层的函数,可以把复杂的任务分解成简单的任务,这种一步一步的分解可以称之为面向过程的程序设计.函数就是面向过程的程序设计的基本单元. ...

随机推荐

  1. 实现QQ、微信、新浪微博和百度第三方登录(Android Studio)

    前言: 对于大多数的APP都有第三方登录这个功能,自己也做过几次,最近又有一个新项目用到了第三方登录,所以特意总结了一下关于第三方登录的实现,并拿出来与大家一同分享: 各大开放平台注册账户获取AppK ...

  2. JS的作用域浅谈

    作为前端小白,总是对JS的作用域有点迷糊,这里稍微研究了一下分享出来,希望和我一样的小白可以学的一点 首先是一个经典的例子: var a=0,b=0; for (var i = 0; i < 1 ...

  3. This Handler class should be static or leaks might occur Android

    首先解释下这句话This Handler class should be static or leaks might occur,大致意思就是说:Handler类应该定义成静态类,否则可能导致内存泄露 ...

  4. B/S 和 C/S两种架构

    一: 什么是B/S(Browser/Server)架构? 应用系统完全放在应用服务器上, 并通过应用服务器同数据库服务器进行通信,系统界面 是通过浏览器来展现的. T是浏览器模式. 优点: 1)客户端 ...

  5. 自动化构建工具gulp简单介绍及使用

    一.简介及安装: gulp是前端开发过程中对代码进行构建的工具,是自动化项目的构建利器:她不仅能对网站资源进行优化,而且在开发过程中很多重复的任务能够使用正确的工具自动完成:使用她,我们不仅可以很愉快 ...

  6. 关于sql、mysql语句的模糊查询分类与详解,包括基本用法和mapper.xml文件里插入写法

    欢迎猿类加qq:2318645572,共同学习进步 实际例子: ssm框架:service业务层->dao层->mappers.xml->junit/test测试 1:service ...

  7. 2017年陕西省网络空间安全技术大赛——种棵树吧——Writeup

    2017年陕西省网络空间安全技术大赛——种棵树吧——Writeup 下载下来的zip解压得到两个jpg图片,在Kali中使用binwalk查看文件类型如下图: 有两个发现: 1111.jpg 隐藏了一 ...

  8. Java设计模式:生成器模式

    问题的提出: 有些类很容易创建对象,直接调用其构造方法,例如Student student = new Student("1001","zhang",21); ...

  9. SQL基础函数

    首先咱们一起来看一下SQL的基本函数 一.聚合函数 二.数学函数 三.字符串函数 四.转换函数 五.时间函数 这样子看起来可能很多,那咱们给变得---------------------------- ...

  10. extj6.0写增删查改(1)-------查询

    本文主要实现的效果是:点击查询按钮,根据form中的条件,在Grid中显示对应的数据(如果form为空,显示全部数据) 一.静态页面 1.查询按钮 { text:'查询', handler: 'onS ...