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

简介: 前言 经常有小伙伴问,如何判断一个元素是否存在,如何判断alert弹窗出来了,如何判断动态的元素等等一系列的判断,在selenium的expected_conditions模块收集了一系列的场景判断方法,这些方法是逢面试必考的!!! expected_conditions一般也简称EC,本篇先介绍下有哪些功能,后续更新中会单个去介绍。

前言

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

expected_conditions一般也简称EC,本篇先介绍下有哪些功能,后续更新中会单个去介绍。
selenium+python高级教程》已出书:selenium webdriver基于Python源码案例

(购买此书送对应PDF版本)

 

一、功能介绍和翻译

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

 

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

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

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

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

相关文章
|
3天前
|
数据采集 Web App开发 测试技术
使用Selenium与WebDriver实现跨浏览器自动化数据抓取
在网络爬虫领域,Selenium与WebDriver是实现跨浏览器自动化数据抓取的利器。本文详细介绍了如何利用Selenium和WebDriver结合代理IP技术提升数据抓取的稳定性和效率。通过设置user-agent和cookie来模拟真实用户行为,避免被网站检测和阻止。文章提供了具体的代码示例,展示了如何配置代理IP、设置user-agent和cookie,并实现了跨浏览器的数据抓取。合理的参数配置能有效减少爬虫被封禁的风险,提高数据抓取效率。
使用Selenium与WebDriver实现跨浏览器自动化数据抓取
|
2天前
|
安全 JavaScript 前端开发
自动化测试的魔法:如何用Python编写你的第一个测试脚本
【8月更文挑战第41天】在软件的世界里,质量是王道。而自动化测试,就像是维护这个王国的骑士,确保我们的软件产品坚不可摧。本文将引导你进入自动化测试的奇妙世界,教你如何使用Python这把强大的魔法杖,编写出能够守护你代码安全的第一道防护咒语。让我们一起开启这场魔法之旅吧!
|
4天前
|
运维 监控 API
自动化运维:使用Python脚本进行日常管理
【9月更文挑战第6天】在现代的IT环境中,自动化运维已成为提升效率、减少人为错误的关键。本文将介绍如何通过Python脚本简化日常的运维任务,包括批量配置管理和日志分析。我们将从基础语法讲起,逐步深入到脚本的实际应用,旨在为读者提供一套完整的解决方案,以实现运维工作的自动化和优化。
11 1
|
9天前
|
运维 Linux 测试技术
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第34天】在快节奏的IT环境中,自动化运维成为提升效率、降低错误率的关键。本文以Python脚本为例,展示如何通过编写简单的脚本来自动化日常运维任务,如批量更改文件权限、自动备份数据等。文章不仅提供代码示例,还探讨了自动化运维带来的益处和实施时应注意的问题。
|
9天前
|
运维 监控 网络安全
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第33天】在本文中,我们将深入探讨如何通过Python脚本来自动化执行常见的运维任务。从基础的服务器健康检查到复杂的部署流程,Python因其简洁和功能强大的特性,成为自动化工具的首选。文章将展示编写Python脚本的基本方法,并通过实际示例演示如何应用于真实场景,旨在帮助读者提升效率,减少重复性工作。
|
9天前
|
运维 监控 Python
自动化运维:使用Python脚本简化日常任务
【8月更文挑战第34天】在数字化时代,高效运维成为企业竞争力的关键。本篇文章将引导你通过Python脚本实现自动化运维,从而提升工作效率和减少人为错误。我们将从简单的文件备份脚本开始,逐步深入到系统监控和自动报告生成,让你的日常工作更加轻松。
|
11天前
|
运维 监控 搜索推荐
自动化运维之宝典:Python脚本实现日常任务管理
在IT运维的日常工作中,重复性任务的自动化处理不仅能提高效率,还能减少人为错误。本文将介绍如何用Python编写简单脚本来自动化常见的运维任务,比如备份文件、监控系统资源和自动更新软件包。我们将一步步构建这些脚本,确保它们易于理解和扩展,最终目标是让读者能够自行定制脚本以适应自己的运维需求。 【8月更文挑战第31天】
|
11天前
|
运维 监控 数据可视化
自动化运维:使用Python脚本进行日志分析
【8月更文挑战第31天】当系统出现问题时,我们通常会查看日志寻找线索。然而,手动阅读大量日志既费时又易出错。本文将介绍如何使用Python脚本自动分析日志,快速定位问题,提高运维效率。我们将从简单的日志读取开始,逐步深入到复杂的正则表达式匹配和错误统计,最后实现一个自动化的日志监控系统。无论你是新手还是老手,这篇文章都将为你提供有价值的参考。让我们一起探索如何用代码解放双手,让运维工作变得更加轻松吧!
|
11天前
|
运维 监控 Python
自动化运维:使用Python脚本实现系统监控
【8月更文挑战第31天】 在现代IT运维管理中,自动化已成为提高效率和准确性的关键。本文将通过一个Python脚本示例,展示如何实现对服务器的自动监控,包括CPU使用率、内存占用以及磁盘空间的实时监测。这不仅帮助运维人员快速定位问题,也减轻了日常监控工作的负担。文章以通俗易懂的语言,逐步引导读者理解并实践自动化监控的设置过程。
|
11天前
|
运维 Kubernetes 监控
自动化运维:使用Python脚本实现系统监控云原生技术实践:Kubernetes在现代应用部署中的角色
【8月更文挑战第31天】在现代IT运维管理中,自动化已成为提高效率和准确性的关键。本文将通过一个Python脚本示例,展示如何实现对服务器的自动监控,包括CPU使用率、内存占用以及磁盘空间的实时监测。这不仅帮助运维人员快速定位问题,也减轻了日常监控工作的负担。文章以通俗易懂的语言,逐步引导读者理解并实践自动化监控的设置过程。 【8月更文挑战第31天】本文旨在探索云原生技术的核心—Kubernetes,如何革新现代应用的开发与部署。通过浅显易懂的语言和实例,我们将一窥Kubernetes的强大功能及其对DevOps文化的影响。你将学会如何利用Kubernetes进行容器编排,以及它如何帮助你的