From: https://www.cnblogs.com/yoyoketang/p/6517477.html

前言:

在脚本中加入太多的sleep后会影响脚本的执行速度,虽然implicitly_wait()这种方法隐式等待方法一定程度上节省了很多时间。

但是一旦页面上某些js无法加载出来(其实界面元素经出来了),左上角那个图标一直转圈,这时候会一直等待的。

一、参数解释

1.这里主要有三个参数:

class WebDriverWait(object):driver, timeout, poll_frequency

2.driver:返回浏览器的一个实例,这个不用多说

3.timeout:超时的总时长

4.poll_frequency:循环去查询的间隙时间,默认0.5秒

以下是源码的解释文档(案例一个是元素出现,一个是元素消失)
    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())
        """

二、元素出现:until()

1.until里面有个lambda函数,这个语法看python文档吧

2.以百度输入框为例

三、元素消失:until_not()

1.判断元素是否消失,是返回Ture,否返回False

备注:此方法未调好,暂时放这

四、参考代码:

# coding:utf-8
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
# 等待时长10秒,默认0.5秒询问一次
WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("kw")).send_keys("yoyo")

# 判断id为kw元素是否消失
is_disappeared = WebDriverWait(driver, 10, 1).\
    until_not(lambda x: x.find_element_by_id("kw").is_displayed())
print is_disappeared

五、WebDriverWait源码

1.WebDriverWait主要提供了两个方法,一个是until(),另外一个是until_not()

以下是源码的注释,有兴趣的小伙伴可以看下

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

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 __repr__(self):
        return '<{0.__module__}.{0.__name__} (session="{1}")>'.format(
            type(self), self._driver.session_id)

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)

Selenium2+python自动化38-显式等待(WebDriverWait)的更多相关文章

  1. selenium自动化之显式等待和EC(expected_conditions)模块

    很多人都有这种经历,selenium脚本当前运行没问题,过了一段时间再运行就报错了,然后过几天又好了.其中的原因估计60%的人都知道,是因为元素加载这块有问题.通常的解决方案就是加上sleep或者隐式 ...

  2. python+selenium 自动化测试——显式等待详解

    1.前言 之前有提到过等待函数,等待函数分为:强制等待(sleep).隐式等待(implicitly_wait),显示等待(WebDriverWait),这次以显示等待方式专门做一次总结,因为我个人是 ...

  3. selenium的webdriver三种等待方式(显式等待WebDriverWait+implicitly_wait隐式等待+sleep强制等待)

    隐式等待是等页面加载,不是等元素!!! 1.显式等待 一个显式等待是你定义的一段代码,用于等待某个条件发生然后再继续执行后续代码.显式等待是等元素加载!!! 2.隐式等待,相当于设置全局的等待,在定位 ...

  4. 显式等待until传入自定义方法

    WebDriverWait(driver,10).until(expected_conditions.element_to_be_clickable(ele)) 通过追踪代码,可以发现上面的eleme ...

  5. 【java+selenium3】隐式等待+显式等待 (七)

    一.隐式等待 -- implicitlyWait 调用方式:driver.manage().timeouts().implicitlyWait(long time, TimeUnit unit); / ...

  6. 基于Selenium2+Java的UI自动化(8)- 显式等待和隐式等待

    一.隐式等待 package com.automation.waits; import java.util.concurrent.TimeUnit; import org.openqa.seleniu ...

  7. Selenium2+python自动化39-关于面试的题

    前言 最近看到群里有小伙伴贴出一组面试题,最近又是跳槽黄金季节,小编忍不住抽出一点时间总结了下, 回答不妥的地方欢迎各位高手拍砖指点.   一.selenium中如何判断元素是否存在? 首先selen ...

  8. Selenium2+python自动化39-关于面试的题【转载】

    前言 最近看到群里有小伙伴贴出一组面试题,最近又是跳槽黄金季节,小编忍不住抽出一点时间总结了下, 回答不妥的地方欢迎各位高手拍砖指点.   一.selenium中如何判断元素是否存在? 首先selen ...

  9. Selenium2+python自动化47-判断弹出框存在(alert_is_present)

    前言 系统弹窗这个是很常见的场景,有时候它不弹出来去操作的话,会抛异常.那么又不知道它啥时候会出来,那么久需要去判断弹窗是否弹出了. 本篇接着Selenium2+python自动化42-判断元素(ex ...

  10. Selenium2+python自动化47-判断弹出框存在(alert_is_present)【转载】

    前言 系统弹窗这个是很常见的场景,有时候它不弹出来去操作的话,会抛异常.那么又不知道它啥时候会出来,那么久需要去判断弹窗是否弹出了. 本篇接着Selenium2+python自动化42-判断元素(ex ...

随机推荐

  1. about Version Control(版本控制)

    what: 版本控制系统是一种软件,它可以帮助您跟踪代码随时间的变化. 在编辑代码时,您告诉版本控制系统对文件进行快照. 版本控制系统将永久保存该快照,以便在以后需要时可以收回它. 如果没有版本控制, ...

  2. Js中的判空

    1.JS 中判断 undefined JavaScript 中有两个特殊数据类型:undefined 和 null var test= undefined; if (typeof(test) == u ...

  3. servlet简单介绍

    什么是Servlet? servlet是一种Java编程语言类,用于扩展托管通过请求 - 响应编程模型访问的应用程序的服务器的功能.尽管servlet可以响应任何类型的请求,但它们通常用于扩展Web服 ...

  4. [洛谷P1417 烹调方案]贪心+dp

    http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3211Dream City Time Limit: 1 Second     ...

  5. C++ 作业 (循环链表构建队列)

    /* author screen name Andromeda_Galaxy; chinese name 杨子俊 */ #include<bits/stdc++.h> using name ...

  6. LeetCode – Number of Islands II

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

  7. 【BZOJ3244】【UOJ#122】【NOI2013]树的计数

    NOI都是酱的题怎么玩啊,哇.jpg 原题: 我们知道一棵有根树可以进行深度优先遍历(DFS)以及广度优先遍历(BFS)来生成这棵树的DFS序以及BFS序.两棵不同的树的DFS序有可能相同,并且它们的 ...

  8. ios存储图片注意

    以下方法可以解决 ios不能长按图片保存到手机的问题 -webkit-touch-callout:default;

  9. pread和pwrite函数

    先来介绍pread函数 [root@bogon mycode]# cat test.c #include<stdio.h> #include<stdlib.h> #includ ...

  10. AspNetCore+Swagger 生成Model描述

    AspNetCore+Swagger 生成Model 描述 前言: 本篇文章实现是基于上一篇文章,进下补充:多余的就不多说了,只是为了实现Model的描述生成:有兴趣的可以结合上一篇的进行实现:如有更 ...