Selenium2+python自动化38-显式等待(WebDriverWait)

摘要:
然而,一旦页面上的一些js无法加载,左上角的图标就会继续旋转。此时,它将一直等待。

前言:

在脚本中加入太多的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
            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())
        """

二、元素出现:until()

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

2.以百度输入框为例

Selenium2+python自动化38-显式等待(WebDriverWait)第1张

三、元素消失:until_not()

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

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

Selenium2+python自动化38-显式等待(WebDriverWait)第2张

四、参考代码:

# 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
            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())
        """
        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)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇git命令行提交流程vue数组赋值变量不影响原数组下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

深入理解linux网络技术内幕读书笔记(十)--帧的接收

Table of Contents 1 概述1.1 帧接收的中断处理 2 设备的开启与关闭 3 队列 4 通知内核帧已接收:NAPI和netif_rx 4.1 NAPI简介4.1.1 NAPI优点 4.2 NAPI所用之net_device字段 4.3 net_rx_action软中断处理函数和NAPI 4.4 新旧驱动程序接口 概...

Web自动化学习(4)

1、Selenium中有哪些不同类型的定位器? 定位器可以看作一个地址,用于在网页中唯一标识一个页面元素,为了准确地识别Web元素 Selenium中有8种不同的定位方式:ID;ClassName;Name;TagName;LinkText;PartialLinkText;Xpath;CSS Selector。 2、什么是XPath? 元素定位方式的一种...

AttributeError: 'WebDriver' object has no attribute 'switchTo'

不在错误中爆发,就在错误中死亡呀. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait driver=webdriver.Firefox() waitdd = WebDriverWait(driver, 30); driver.get...

appium简明教程(11)——使用resource id定位(仅支持安卓4.3以上系统)

上一节乙醇带大家了解了appium的定位策略。实际上appium的控件定位方式是完全遵守webdriver的mobile扩展协议的。 这一节将分享一下如何使用resource id来定位android策略。 什么是resource id,这个不属于本文的范畴,大家可以点这里了解。 我们可以有两种方式来使用resource id进行定位: 使用findEl...

webdriver与JS操作浏览器元素

1、JQuery的选择器实例 语法 描述 $(this) 当前 HTML 元素 $("p") 所有 <p> 元素 $("p.intro") 所有 的 <p> 元素 $(".intro") 所有 的元素 $("#intro") 的元素 $("ul li:first") 每个 <ul> 的第一个...

python+selenium获取禅道所有Bug标题

前言: 对于一组很多的数据,一个页面加载不完,需要分页加载,比如禅道的Bug数,一页默认是20个(自己可以根据需求更改),这时就有了第二页,第三页等等。 这时如果要获取所有的Bug标题来怎么做呢? 点击下一页Bug,你会发现url的变化,就只有最后一个数字改变,如下图: 大体思路: 获取所有url→ddt驱动获取每一页的数据 步骤: 第一步:获取所有u...