selenium3源码解析Python篇(二)-异常类

本篇所讲的是关于selenium源码中的异常类

通过源码我们可以得知selenium的异常有很多
ErrorInResponseException
InvalidSwitchToTargetException
NoSuchFrameException
NoSuchWindowException
NoSuchElementException
NoSuchAttributeException
……

以NoSuchElementException为例:
源码是这么描述的:
selenium3源码解析Python篇(二)-异常类_第1张图片
由此我们可以了解到,遇到此种错误,我们需要去检查以下几项:
1.您在查找中使用的选择器
2.元素在查找操作时可能尚未出现在屏幕上
3.网页仍在加载,如何编写等待包装器以等待元素出现

接下来我们介绍下selenium webdriver中常见的异常:
NoSuchElementException 如上例子所属,属于没找到元素异常
NoSuchFrameException 没找到iframe异常
NoSuchWindowException 没找到窗口句柄异常
NoSuchAttributeException 属性错误异常(id=“kw” id为元素,kw为属性)
NoAlertPresentException 没找到alert弹出框异常
ElementNotVisibleException 元素不可见异常
ElementNotSelectableException 元素没有被选中异常
TimeoutException 查找元素超时

部分异常源码如下:
selenium3源码解析Python篇(二)-异常类_第2张图片
Exceptions that may happen in all the webdriver code:
既然源码里已经这么说了,我们要想了解selenium webdriver的异常,这块可是要好好看看的。

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

上面这块是webdriver异常类的基类,其他异常均继承此基类
关于初始化中的三个参数:
msg:异常信息
screen:异常截图
stacktrace:异常堆栈信息

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

关于NoSuchElementException类为pass空实现,此处只是占位,定义一个规范,后续由其子类具体实现

你可能感兴趣的:(自动化之路)