【问题标题】:Try...except not catching NoSuchElementException in python and selenium [duplicate]尝试...除了没有在 python 和 selenium 中捕获 NoSuchElementException [重复]
【发布时间】:2016-03-15 12:29:40
【问题描述】:

我有以下代码:

def test_counter(self):
    try:
        if self.driver.find_element_by_id(self.counter).text == 'texttexttext':
            return True
    except NoSuchElementException and StaleElementReferenceException:
        self.fix_error()
    return False

我不知道为什么NoSuchElementExceptionStaleElementReferenceException 没有被抓到。

【问题讨论】:

    标签: python selenium


    【解决方案1】:

    A and B become B if both A and B is truth values. 所以NoSuchElementException and StaleElementReferenceException 变成StaleElementReferenceException;代码仅捕获该异常。

    >>> NoSuchElementException and StaleElementReferenceException
    <class 'selenium.common.exceptions.StaleElementReferenceException'>
    

    您需要使用except (NoSuchElementException, StaleElementReferenceException): 来捕获这两个异常。

    【讨论】:

    • 嗯...from foobar import * 不推荐。
    • @KevinGuan:对于一个命名空间良好的包,假设它真的只包含selenium 特定的异常,它还不错。需要限定您可能必须处理的所有异常,或者按名称显式导入它们,这很烦人。
    • 旁注:如果您需要捕获异常并存储它,您可以使用except (NoSuchElementException, StaleElementReferenceException) as somename:(其中somename 通常只是e,但我想澄清一下名称是您选择的任何名称)。
    • @KevinGuan,我这样做是为了简洁。
    • @KevinGuan,我删除了导入行,因为它不是答案的重点。感谢您的反馈。
    【解决方案2】:

    改变这一行:

    except NoSuchElementException and StaleElementReferenceException:
    

    进入:

    except (NoSuchElementException, StaleElementReferenceException):
    

    这就是原因:

    >>> NoSuchElementException and StaleElementReferenceException
    StaleElementReferenceException
    

    and 首先检查NoSuchElementException 是否为真。既然是这种情况,它会检查StaleElementReferenceException 是否为真。因为它也是 true,所以它返回这个类。

    使用pylint,它会警告你:

    Exception to catch is the result of a binary "and" operation (binary-op-exception)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 2022-01-07
      • 2016-01-10
      • 2012-07-15
      • 2016-07-12
      相关资源
      最近更新 更多