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

前言:

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

学习过程中有遇到疑问的,可以加selenium(python+java) QQ群交流:232607095

appium交流QQ群:512200893

可以在pc上收藏我的博客地址:http://www.cnblogs.com/yoyoketang/地址很好记哦,前面是cnblogs地址,后面是yoyoketang,收藏这个地址,你懂得!

(0)

相关推荐

  • 【python selenium的web自动化】- PageObject模式解析及案例

    https://www.cnblogs.com/miki-peng/category/1942527.html PO模式 Page Object(简称PO)模式,是Selenium实战中最为流行,并且 ...

  • Python爬取淘宝销量数据!这年头数据就是钱啊

    前言 一.基本环境配置 python版本:python 3.8.3 编辑器:anaconda3下的spyder 浏览器版本:Google Chrome 87.0.4280.88 浏览器驱动器:本文通过 ...

  • scrapy实践之中间件的使用

    在scrapy框架中,Downloader Middlewares 称之为下载中间件, 可以对爬虫的requests请求进行封装处理,典型的应用有以下3种 1. 添加用户代理 所有的中间件代码都保存在 ...

  • Selenium2+python自动化36-判断元素存在

    前言 最近有很多小伙伴在问如何判断一个元素是否存在,这个方法在selenium里面是没有的,需要自己写咯. 元素不存在的话,操作元素会报错,或者元素有多个,不唯一的时候也会报错.本篇介绍两种判断元素存 ...

  • Selenium2+python自动化37-爬页面源码(page_source)

    前言 有时候通过元素的属性的查找页面上的某个元素,可能不太好找,这时候可以从源码中爬出想要的信息.selenium的page_source方法可以获取到页面源码. selenium的page_sour ...

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

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

  • Selenium2+python自动化40-cookie相关操作

    前言 虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录. 登录后换账号登录时候,也可作为后置条件去删除cookie ...

  • Selenium2+python自动化41-绕过验证码(add_cookie)

    前言 验证码这种问题是比较头疼的,对于验证码的处理,不要去想破解方法,这个验证码本来就是为了防止别人自动化登录的.如果你能破解,说明你们公司的验证码安全级别不高,那就需要提高级别了. 处理验证码,要么 ...

  • Selenium2+python自动化42-判断元素(expected_conditions)

    前言 经常有小伙伴问,如何判断一个元素是否存在,如何判断alert弹窗出来了,如何判断动态的元素等等一系列的判断,在selenium的expected_conditions模块收集了一系列的场景判断方 ...

  • Selenium2+python自动化43-判断title(title_is)

    前言 获取页面title的方法可以直接用driver.title获取到,然后也可以把获取到的结果用做断言. 本篇介绍另外一种方法去判断页面title是否与期望结果一种,用到上一篇Selenium2+p ...

  • Selenium2+python自动化44-元素定位参数化(find_element)

    前言 元素定位常用的有八种方法,这个能看到这一篇的小伙伴都知道了,那么有没有一种方法,可以把常用的八种定位合为一种呢?也就是把定位的方式参数化,如id,name.css等设置为一个参数,这样只需维护定 ...

  • Selenium2+python自动化45-18种定位方法(find_elements)

    前言 江湖传言,武林中流传八种定位,其中xpath是宝刀屠龙,css是倚天剑. 除了这八种,其实还有十种定位方法,眼看就快失传了,今天小编让失传已久的定位方法重出江湖! 一.十八种定位方法 前八种是大 ...