前言

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

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

一、功能介绍和翻译

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

title_contains : 判断当前页面的title是否包含预期字符串,返回布尔值

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

二、查看源码和注释

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

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

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

Selenium2+python自动化42-判断元素(expected_conditions)【转载】的更多相关文章

  1. Selenium2+python自动化52-unittest执行顺序【转载】

    前言 很多初学者在使用unittest框架时候,不清楚用例的执行顺序到底是怎样的.对测试类里面的类和方法分不清楚,不知道什么时候执行,什么时候不执行. 本篇通过最简单案例详细讲解unittest执行顺 ...

  2. Selenium2+python自动化20-Excel数据参数化【转载】

    前言 问: Python 获取到Excel一列值后怎么用selenium录制的脚本中参数化,比如对登录用户名和密码如何做参数化? 答:可以使用xlrd读取Excel的内容进行参数化.当然为了便于各位小 ...

  3. Selenium2+python自动化36-判断元素存在【转载】

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

  4. Selenium2+python自动化17-JS处理滚动条【转载】

    前言 selenium并不是万能的,有时候页面上操作无法实现的,这时候就需要借助JS来完成了. 常见场景: 当页面上的元素超过一屏后,想操作屏幕下方的元素,是不能直接定位到,会报元素不可见的. 这时候 ...

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

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

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

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

  7. Selenium2+python自动化6-八种元素元素定位(Firebug和firepath)【转载】

    前言 自动化只要掌握四步操作:获取元素,操作元素,获取返回结果,断言(返回结果与期望结果是否一致),最后自动出测试报告.本篇主要讲如何用firefox辅助工具进行元素定位.元素定位在这四个环节中是至关 ...

  8. Selenium2+python自动化35-获取元素属性【转载】

    前言 通常在做断言之前,都要先获取界面上元素的属性,然后与期望结果对比.本篇介绍几种常见的获取元素属性方法. 一.获取页面title 1.有很多小伙伴都不知道title长在哪里,看下图左上角. 2.获 ...

  9. Selenium2+python自动化12-操作元素(键盘和鼠标事件)【转载】

    前言 在前面的几篇中重点介绍了一些元素的到位方法,到位到元素后,接下来就是需要操作元素了.本篇总结了web页面常用的一些操作元素方法,可以统称为行为事件 有些web界面的选项菜单需要鼠标悬停在某个元素 ...

随机推荐

  1. Git&GitHub&GitBook

    一.定义 Git(分布式版本控制系统) GitHub gitHub是一个面向开源及私有软件项目的托管平台,因为只支持git 作为唯一的版本库格式进行托管,故名gitHub. gitHub于2008年4 ...

  2. 软工实践Beta冲刺(3/7)

    队名:起床一起肝活队 组长博客:博客链接 作业博客:班级博客本次作业的链接 组员情况 组员1(队长):白晨曦 过去两天完成了哪些任务 描述: 1.界面的修改与完善 展示GitHub当日代码/文档签入记 ...

  3. PAT java大数 A+B和C

    题目描述: 给定区间[-, ]内的3个整数A.B和C,请判断A+B是否大于C. 输入格式: 输入第1行给出正整数T(<=),是测试用例的个数.随后给出T组测试用例,每组占一行,顺序给出A.B和C ...

  4. lintcode-98-链表排序

    98-链表排序 在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序. 样例 给出 1->3->2->null,给它排序变成 1->2->3->nu ...

  5. iOS-调用百度地图,苹果自带地图,高德地图,谷歌地图导航方法

    - (void)actionSheet : (ServiceNetworkModel *)model{ __block NSString *urlScheme = @"demoURI://& ...

  6. [转] UnityVS(Visual Studio Tools For Unity)的安装与使用

    一些废话 Unity 的开发者们,尤其是微软系的Unity开发者们,用Mono是不是烦死了?你是不是跟我一样,用vs来写代码,用Mono来跟踪调试?好麻烦啊好麻烦. 也许你会说,傻逼你不会用Unity ...

  7. 6for Java

    class Check{ public boolean validate(String name,   String password){  if(name.equals("xuzhaoni ...

  8. Redis能做什么?不能做什么?

    https://blog.csdn.net/u014229282/article/details/81174202 最近阅读了<redis设计与实现>,这是一本比较枯燥的书,毕竟涉及到re ...

  9. iOS 定时器开发详情

    目录 概述 NSTimer performSelector GCD timer CADisplayLink 一.概述 在平时的开发任务中,定时器是我们常用的技术.这一节我们来学习iOS怎么使用定时器. ...

  10. hdu 1207 汉诺塔II (DP+递推)

    汉诺塔II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submi ...