web自动化 selenium webdriver的等待方式概述

背景

自动化测试系统运行中,会由于网络等原因导致定位元素超时失败,从而造成测试结果的不准确性。需要合理的等待机制,保障自动化测试系统的稳定性和健壮性。
笔者将在参考如下博文的基础上,再表述自己的理解,完成这篇关于web自动化中等待机制的总结。关于等待方法的使用请参考如下博文:
参考:https://blog.csdn.net/Wuli_SmBug/article/details/82053372

三种等待方式

  • 强制等待
  • 隐式等待
  • 显示等待

强制等待:为python中time对象中的sleep(函数),强制阻塞调用进程(线程)指定时间。
隐式等待:为webdriver对象提供的一个方法,webdriver.implicitly_wait(self, time_to_wait),参数time_to_wait的时间单位是秒。其作用对象是整个webdriver,从应用层面,可以理解为作用对象为自动化测试系统中的浏览器。这是与显示等待最大的区别。为了通俗易懂,作用对象是整个浏览器的含义可以这样理解:隐式等待是自动化测试中的浏览器自身的一种属性。从通过webdriver.implicitly_wait(self, time_to_wait)方法设置隐式等待的那一刻起,自动化测试中的浏览器就会根据这一属性遵守相应规则,所以隐式等待的作用周期设置隐式等待那一刻到浏览器关闭的这一生命周期。隐式等待的规则:首先,隐式等待不像强制等待,阻塞调用进程(线程)的运行,隐式等待不影响脚本的运行速度。其次,由于隐式等待的作用对象是整个浏览器,所以其规则是等待浏览器的当前页面全部加载完成,才算是等待成功,如果当前页面没有全部加载成功,则继续等待,直到超时后抛出异常。虽然我们需要等待是因为我们需要保障稳定的定位到某个元素,但隐式等待的机制决定了,及时目标元素一开始就已经加载完毕,但是由于当前页面没有加载完成,那么就不会执行定位语句以及之后的脚本。以上,是笔者理解的隐式等待的特点。总结来说,隐式等待使用简洁,但会造成自动化测试运行中的时间冗余。
显示等待:通过WebDriverWait对象来实现。具体地说,通过WebDriverWait对象中的until(self, method, message=’’)方法或者until_not(self, method, message=’’)方法来实现。其中参数method为一个函数对象或可执行的实例对象。强制等待的作用范围和作用对象都是当时指定的某个元素。使用时通常结合expected_conditions模块中的各种关于元素状态的类(该模块中的各种类实现了基于元素的各种预期条件判断)。来实现通过判断指定元素是否满足指定条件,来确认强制等待的结果。如果等待成功,则定位成功,继续执行定位后的脚本,如果等待失败,则继续等待,直到超时抛出异常。

总结

  • 强制等待的作用对象是调用进程(线程)
  • 隐式等待的作用对象webdriver,可以理解为整个浏览器。
  • 强制等待的作用对象是指定元素。

从上到下,等待处理机制的颗粒度越来越细,使用效果因场合而已,但对自动化测试系统的健壮性和稳定性是越来越好。

最后,贴上配合强制等待使用的expected_conditions模块中的各种针对元素判断的预期条件。不过抱歉的是,是贴源代码,当然相信网上肯定也有类似的表格,虫师的自动化测试实战书籍也有这些条件的表格式整理。

# 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.

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
from selenium.webdriver.remote.webdriver import WebElement

"""
 * 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 url_contains(object):
    """ An expectation for checking that the current url contains a
    case-sensitive substring.
    url is the fragment of url expected,
    returns True when the url matches, False otherwise
    """
    def __init__(self, url):
        self.url = url

    def __call__(self, driver):
        return self.url in driver.current_url


class url_matches(object):
    """An expectation for checking the current url.
    pattern is the expected pattern, which must be an exact match
    returns True if the url matches, false otherwise."""
    def __init__(self, pattern):
        self.pattern = pattern

    def __call__(self, driver):
        import re
        match = re.search(self.pattern, driver.current_url)

        return match is not None


class url_to_be(object):
    """An expectation for checking the current url.
    url is the expected url, which must be an exact match
    returns True if the url matches, false otherwise."""
    def __init__(self, url):
        self.url = url

    def __call__(self, driver):
        return self.url == driver.current_url


class url_changes(object):
    """An expectation for checking the current url.
    url is the expected url, which must not be an exact match
    returns True if the url is different, false otherwise."""
    def __init__(self, url):
        self.url = url

    def __call__(self, driver):
        return self.url != driver.current_url


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 visibility_of_any_elements_located(object):
    """ An expectation for checking that there is at least one element visible
    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 [element for element in _find_elements(driver, self.locator) if _element_if_visible(element)]


class visibility_of_all_elements_located(object):
    """ An expectation for checking that all elements are present on the DOM of a
    page and visible. Visibility means that the elements are not only displayed
    but also has a height and width that is greater than 0.
    locator - used to find the elements
    returns the list of WebElements once they are located and visible
    """
    def __init__(self, locator):
        self.locator = locator

    def __call__(self, driver):
        try:
            elements = _find_elements(driver, self.locator)
            for element in elements:
                if _element_if_visible(element, visibility=False):
                    return False
            return elements
        except StaleElementReferenceException:
            return False


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.target = locator

    def __call__(self, driver):
        try:
            target = self.target
            if not isinstance(target, WebElement):
                target = _find_element(driver, target)
            return _element_if_visible(target, 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 invisibility_of_element(invisibility_of_element_located):
    """ An Expectation for checking that an element is either invisible or not
    present on the DOM.

    element is either a locator (text) or an WebElement
    """
    def __init(self, element):
        self.target = element


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:
            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 number_of_windows_to_be(object):
    """ An expectation for the number of windows to be a certain value."""

    def __init__(self, num_windows):
        self.num_windows = num_windows

    def __call__(self, driver):
        return len(driver.window_handles) == self.num_windows


class new_window_is_opened(object):
    """ An expectation that a new window will be opened and have the number of
    windows handles increase"""

    def __init__(self, current_handles):
        self.current_handles = current_handles

    def __call__(self, driver):
        return len(driver.window_handles) > len(self.current_handles)


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
            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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值