Selenium2+python自动化57-捕获异常(NoSuchElementException)

简介: 前言 在定位元素的时候,经常会遇到各种异常,为什么会发生这些异常,遇到异常又该如何处理呢? 本篇通过学习selenium的exceptions模块,了解异常发生的原因。 selenium+python高级教程》已出书:selenium webdriver基于Python源码案例 (购买此书送对应PDF版本)   一、发生异常 1.

前言

在定位元素的时候,经常会遇到各种异常,为什么会发生这些异常,遇到异常又该如何处理呢?

本篇通过学习selenium的exceptions模块,了解异常发生的原因。

selenium+python高级教程》已出书:selenium webdriver基于Python源码案例

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

 

一、发生异常

1.打开博客首页,定位“新随笔”元素,此元素id="blog_nav_newpost"

2.为了故意让它定位失败,我在元素属性后面加上xx

3.运行失败后如下图所示,程序在查找元素的这一行发生了中断,不会继续执行click事件了

 

二、捕获异常

1.为了让程序继续执行,我们可以用try...except...捕获异常。捕获异常后可以打印出异常原因,这样以便于分析异常原因

2.从如下异常内容可以看出,发生异常原因是:NoSuchElementException

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"blog_nav_newpostxx"}

3.从selenium.common.exceptions 导入 NoSuchElementException类

 

三、参考代码:

# coding:utf-8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox()
driver.get("http://www.cnblogs.com/yoyoketang/")
# 定位首页"新随笔"
try:
    element = driver.find_element("id", "blog_nav_newpostxx")
except NoSuchElementException as msg:
    print u"查找元素异常%s"%msg

# 点击该元素   # 交流QQ群:232607095
else:
    element.click()

 

四、selenium常见异常

1.NoSuchElementException:没有找到元素

2.NoSuchFrameException:没有找到iframe

3.NoSuchWindowException:没找到窗口句柄handle

4.NoSuchAttributeException:属性错误

5.NoAlertPresentException:没找到alert弹出框

6.lementNotVisibleException:元素不可见

7.ElementNotSelectableException:元素没有被选中

8.TimeoutException:查找元素超时

 

五、其它异常与源码

1.在Lib目录下:\Lib\site-packages\selenium\common有兴趣的可以看看

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

"""
Exceptions that may happen in all the webdriver code.
"""


class WebDriverException(Exception):
    """
    Base webdriver exception.
    """

    def __init__(self, msg=None, screen=None, stacktrace=None):
        self.msg = msg
        self.screen = screen
        self.stacktrace = stacktrace

    def __str__(self):
        exception_msg = "Message: %s\n" % self.msg
        if self.screen is not None:
            exception_msg += "Screenshot: available via screen\n"
        if self.stacktrace is not None:
            stacktrace = "\n".join(self.stacktrace)
            exception_msg += "Stacktrace:\n%s" % stacktrace
        return exception_msg


class ErrorInResponseException(WebDriverException):
    """
    Thrown when an error has occurred on the server side.

    This may happen when communicating with the firefox extension
    or the remote driver server.
    """
    def __init__(self, response, msg):
        WebDriverException.__init__(self, msg)
        self.response = response


class InvalidSwitchToTargetException(WebDriverException):
    """
    Thrown when frame or window target to be switched doesn't exist.
    """
    pass


class NoSuchFrameException(InvalidSwitchToTargetException):
    """
    Thrown when frame target to be switched doesn't exist.
    """
    pass


class NoSuchWindowException(InvalidSwitchToTargetException):
    """
    Thrown when window target to be switched doesn't exist.

    To find the current set of active window handles, you can get a list
    of the active window handles in the following way::

        print driver.window_handles

    """
    pass


class NoSuchElementException(WebDriverException):
    """
    Thrown when element could not be found.

    If you encounter this exception, you may want to check the following:
        * Check your selector used in your find_by...
        * Element may not yet be on the screen at the time of the find operation,
        (webpage is still loading) see selenium.webdriver.support.wait.WebDriverWait()
        for how to write a wait wrapper to wait for an element to appear.
    """
    pass


class NoSuchAttributeException(WebDriverException):
    """
    Thrown when the attribute of element could not be found.

    You may want to check if the attribute exists in the particular browser you are
    testing against.  Some browsers may have different property names for the same
    property.  (IE8's .innerText vs. Firefox .textContent)
    """
    pass


class StaleElementReferenceException(WebDriverException):
    """
    Thrown when a reference to an element is now "stale".

    Stale means the element no longer appears on the DOM of the page.


    Possible causes of StaleElementReferenceException include, but not limited to:
        * You are no longer on the same page, or the page may have refreshed since the element
        was located.
        * The element may have been removed and re-added to the screen, since it was located.
        Such as an element being relocated.
        This can happen typically with a javascript framework when values are updated and the
        node is rebuilt.
        * Element may have been inside an iframe or another context which was refreshed.
    """
    pass


class InvalidElementStateException(WebDriverException):
    """
    """
    pass


class UnexpectedAlertPresentException(WebDriverException):
    """
    Thrown when an unexpected alert is appeared.

    Usually raised when when an expected modal is blocking webdriver form executing any
    more commands.
    """
    def __init__(self, msg=None, screen=None, stacktrace=None, alert_text=None):
        super(UnexpectedAlertPresentException, self).__init__(msg, screen, stacktrace)
        self.alert_text = alert_text

    def __str__(self):
        return "Alert Text: %s\n%s" % (self.alert_text, super(UnexpectedAlertPresentException, self).__str__())


class NoAlertPresentException(WebDriverException):
    """
    Thrown when switching to no presented alert.

    This can be caused by calling an operation on the Alert() class when an alert is
    not yet on the screen.
    """
    pass


class ElementNotVisibleException(InvalidElementStateException):
    """
    Thrown when an element is present on the DOM, but
    it is not visible, and so is not able to be interacted with.

    Most commonly encountered when trying to click or read text
    of an element that is hidden from view.
    """
    pass


class ElementNotSelectableException(InvalidElementStateException):
    """
    Thrown when trying to select an unselectable element.

    For example, selecting a 'script' element.
    """
    pass


class InvalidCookieDomainException(WebDriverException):
    """
    Thrown when attempting to add a cookie under a different domain
    than the current URL.
    """
    pass


class UnableToSetCookieException(WebDriverException):
    """
    Thrown when a driver fails to set a cookie.
    """
    pass


class RemoteDriverServerException(WebDriverException):
    """
    """
    pass


class TimeoutException(WebDriverException):
    """
    Thrown when a command does not complete in enough time.
    """
    pass


class MoveTargetOutOfBoundsException(WebDriverException):
    """
    Thrown when the target provided to the `ActionsChains` move()
    method is invalid, i.e. out of document.
    """
    pass


class UnexpectedTagNameException(WebDriverException):
    """
    Thrown when a support class did not get an expected web element.
    """
    pass


class InvalidSelectorException(NoSuchElementException):
    """
    Thrown when the selector which is used to find an element does not return
    a WebElement. Currently this only happens when the selector is an xpath
    expression and it is either syntactically invalid (i.e. it is not a
    xpath expression) or the expression does not select WebElements
    (e.g. "count(//input)").
    """
    pass


class ImeNotAvailableException(WebDriverException):
    """
    Thrown when IME support is not available. This exception is thrown for every IME-related
    method call if IME support is not available on the machine.
    """
    pass


class ImeActivationFailedException(WebDriverException):
    """
    Thrown when activating an IME engine has failed.
    """
    pass

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

觉得对你有帮助,就在右下角点个赞吧,感谢支持!

 

相关文章
|
14天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
2天前
|
数据采集 前端开发 测试技术
《手把手教你》系列技巧篇(三十一)-java+ selenium自动化测试- Actions的相关操作-番外篇(详解教程)
【4月更文挑战第23天】本文介绍了网页中的滑动验证码的实现原理和自动化测试方法。作者首先提到了网站的反爬虫机制,并表示在本地创建一个没有该机制的网页,然后使用谷歌浏览器进行验证。接着,文章详细讲解了如何使用WebElement的click()方法以及Action类提供的API来模拟鼠标的各种操作,如右击、双击、悬停和拖动。
6 2
|
2天前
|
Java 测试技术 持续交付
深入理解与应用Selenium WebDriver进行自动化测试
【4月更文挑战第25天】 在现代软件开发过程中,自动化测试已成为确保产品质量和加速市场发布的关键步骤。Selenium WebDriver作为业界广泛采用的自动化测试工具之一,提供了一种灵活且高效的方式来模拟用户与Web应用程序交互。本文将探讨Selenium WebDriver的核心概念、架构以及实际应用中的技巧和最佳实践。通过深入分析其工作原理及常见问题解决方案,旨在帮助测试工程师提升测试效率,确保测试结果的准确性和可靠性。
|
3天前
|
Web App开发 数据采集 Java
《手把手教你》系列技巧篇(三十)-java+ selenium自动化测试- Actions的相关操作下篇(详解教程)
【4月更文挑战第22天】本文介绍了在测试过程中可能会用到的两个功能:Actions类中的拖拽操作和划取字段操作。拖拽操作包括基本讲解、项目实战、代码设计和参考代码,涉及到鼠标按住元素并将其拖动到另一个元素上或指定位置。划取字段操作则介绍了如何在一段文字中随机选取一部分,包括项目实战、代码设计和参考代码。此外,文章还提到了滑动验证的实现,并提供了相关的代码示例。
31 2
|
3天前
|
测试技术 API 网络架构
Python的api自动化测试 编写测试用例
【4月更文挑战第18天】使用Python进行API自动化测试,可以结合`requests`库发送HTTP请求和`unittest`(或`pytest`)编写测试用例。以下示例: 1. 安装必要库:`pip install requests unittest` 2. 创建`test_api.py`,导入库,定义基础URL。 3. 创建继承自`unittest.TestCase`的测试类,包含`setUp`和`tearDown`方法。 4. 编写测试用例,如`test_get_users`,检查响应状态码和内容。 5. 运行测试:`python -m unittest test_api.py`
12 2
|
3天前
|
JSON 测试技术 API
Python的Api自动化测试使用HTTP客户端库发送请求
【4月更文挑战第18天】在Python中进行HTTP请求和API自动化测试有多个库可选:1) `requests`是最流行的选择,支持多种请求方法和内置JSON解析;2) `http.client`是标准库的一部分,适合需要低级别控制的用户;3) `urllib`提供URL操作,适用于复杂请求;4) `httpx`拥有类似`requests`的API,提供现代特性和异步支持。根据具体需求选择,如多数情况`requests`已足够。
9 3
|
3天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
21 0
|
4天前
|
测试技术 持续交付 API
Python的UI自动化测试
【4月更文挑战第17天】Python UI自动化测试涉及Selenium(Web)、Appium(移动应用)和PyQt(桌面应用)等框架。基本步骤包括确定测试目标、选择合适框架、安装配置、编写测试脚本、运行调试以及集成到CI/CD流程。注意自动化测试不能完全取代人工测试,应根据需求平衡使用。
8 1
|
4天前
|
前端开发 测试技术 C++
Python自动化测试面试:unittest、pytest与Selenium详解
【4月更文挑战第19天】本文聚焦Python自动化测试面试,重点讨论unittest、pytest和Selenium三大框架。unittest涉及断言、TestSuite和覆盖率报告;易错点包括测试代码冗余和异常处理。pytest涵盖fixtures、参数化测试和插件系统,要注意避免过度依赖unittest特性。Selenium的核心是WebDriver操作、等待策略和测试报告生成,强调智能等待和元素定位策略。掌握这些关键点将有助于提升面试表现。
19 0
|
5天前
|
XML Web App开发 测试技术
python的Web自动化测试
【4月更文挑战第16天】Python在Web自动化测试中广泛应用,借助Selenium(支持多浏览器交互)、BeautifulSoup(解析HTML/XML)、Requests(发送HTTP请求)和Unittest(测试框架)等工具。测试步骤包括环境搭建、编写测试用例、初始化浏览器、访问页面、操作元素、验证结果、关闭浏览器及运行报告。注意浏览器兼容性、动态内容处理和错误处理。这些组合能提升测试效率和质量。
11 6

热门文章

最新文章