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

前言

经常有小伙伴问,如何判断一个元素是否存在,如何判断alert弹窗出来了,如何判断动态的元素等等一系列的判断,在selenium的expected_conditions模块收集了一系列的场景判断方法,这些方法是逢面试必考的!!!

expected_conditions一般也简称EC,本篇先介绍下有哪些功能,后续更新中会单个去介绍。

一、功能介绍和翻译

title_is:

判断当前页面的title是否完全等于(a==b)预期字符串,返回布尔值 title_contains :

判断当前页面的title是否包含(a in b)预期字符串,返回布尔值 presence_of_element_located :

判断某个元素是否被加到了dom树里,并不代表该元素一定可见 visibility_of_element_located :

判断某个元素是否可见. 可见代表元素非隐藏,并且元素的宽和高都不等于0 visibility_of :

跟上面的方法做一样的事情,只是上面的方法要传入locator,这个方法直接传定位到的element就好了 presence_of_all_elements_located :

判断是否至少有1个元素存在于dom树中。举个例子,如果页面上有n个元素的class都是'column-md-3',那么只要有1个元素存在,这个方法就返回True text_to_be_present_in_element :

判断某个元素中的text是否 包含 了预期的字符串 text_to_be_present_in_element_value :

判断某个元素中的value属性是否 包含 了预期的字符串 frame_to_be_available_and_switch_to_it :

判断该frame是否可以switch进去,如果可以的话,返回True并且switch进去,否则返回False invisibility_of_element_located :

判断某个元素中是否不存在于dom树或不可见 element_to_be_clickable :

判断某个元素中是否可见并且是enable的,这样的话才叫clickable staleness_of :

等某个元素从dom树中移除,注意,这个方法也是返回True或False element_to_be_selected :

判断某个元素是否被选中了,一般用在下拉列表 element_selection_state_to_be :

判断某个元素的选中状态是否符合预期 element_located_selection_state_to_be :

跟上面的方法作用一样,只是上面的方法传入定位到的element,而这个方法传入locator alert_is_present :

判断页面上是否存在alert

selenium(python+java) QQ群交流:232607095

二、查看源码和注释

1.打开python里这个目录l可以找到:Lib\site-packages\selenium\webdriver\support\expected_conditions.py

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

本篇的判断方法和场景很多,先贴出来,后面慢慢更新,详细讲解每个的功能的场景和用法。

这些方法是写好自动化脚本,提升性能的必经之路,想做好自动化,就得熟练掌握。

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

另外成立了python接口自动化QQ群:226296743

原文发布于微信公众号 - 从零开始学自动化测试(yoyoketang)

原文发表时间:2017-03-14

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏友弟技术工作室

golang之Struct什么是结构体struct?

最近在复习golang,学习的东西,如果不使用,很快就会忘记。所以,准备复习完golang,做一个练手的小项目,加深对golang的学习。今天开始公司,进入封闭...

5846
来自专栏jeremy的技术点滴

py3_cookbook_notes_01

3298
来自专栏mySoul

设计模式 里氏替换原则

在场景中,三毛需要什么枪支,就直接new 出一个枪支即可,然后其内通过抽象类获取到对象,然后对齐进行修饰

1246
来自专栏咸鱼不闲

jsoup爬虫工具的简单使用

解决方案: 1.通过url 获得doucment对象, 2.调用select()等方法获得Elements对象, 3.调用.text()等方法,获得自己想要的内...

4204
来自专栏对角另一面

读Zepto源码之样式操作

这篇依然是跟 dom 相关的方法,侧重点是操作样式的方法。 读Zepto源码系列文章已经放到了github上,欢迎star: reading-zepto 源码版...

2400
来自专栏一直在跳坑然后爬坑

如何通过自定义View方式模拟SVG并实现动画

3.然后我们要进行对五角星动画的裁剪,涉及到的方法是PathMeasure的getLength和getSegment方法,getLength()不用多说,就是用...

1141
来自专栏章鱼的慢慢技术路

Go语言相关练习_选择题(1)

 解析:Go语言的内存回收机制规定,只要有一个指针指向引用一个变量,那么这个变量就不会被释放(内存逃逸),因此在Go语言中返回函数参数或临时变量是安全的。

631
来自专栏Golang语言社区

浅谈Go语言中的结构体struct & 接口Interface & 反射

结构体struct struct 用来自定义复杂数据结构,可以包含多个字段(属性),可以嵌套;

2174
来自专栏GreenLeaves

C# String.Format的格式限定符与Format方法将多个对象格式化一个字符串原理

Format方法将多个对象格式化成一个字符串Format方法解析格式字符串的原理:

1162
来自专栏Micro_awake web

Vue学习3:计算属性computed与监听器

1602

扫码关注云+社区

领取腾讯云代金券