Try...except not catching NoSuchElementException in python and selenium

时间:2015-12-10 01:39:05

标签: python selenium

I have this code below:

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

And I cannot figure out why the NoSuchElementException or the StaleElementReferenceException are not being caught.

2 个答案:

答案 0 :(得分:6)

A and B become B if both A and B is truth values. So NoSuchElementException and StaleElementReferenceException become StaleElementReferenceException; The code is catching that exception only.

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

You need to use except (NoSuchElementException, StaleElementReferenceException): to catch both exceptions.

答案 1 :(得分:5)

Change this line:

except NoSuchElementException and StaleElementReferenceException:

into:

except (NoSuchElementException, StaleElementReferenceException):

This is the reason:

>>> NoSuchElementException and StaleElementReferenceException
StaleElementReferenceException

The and checks if NoSuchElementException is true first. Since this is case, it checks if StaleElementReferenceException is true. Because it also true, it returns this class.

Use pylint and it will warn you about this:

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