Selenium work around 'TimeoutException' is not defined?

Viewed 4726

I want to work around the TimeOutException in Python Selenium.

This happens:

1.) Open Browser, Call URL
2.) Trying to find Element
2.1) Works sometimes
2.2) Works not sometimes and throws TimeoutException
3.) Should look for other elements

I can never reach step 3.) after we have hit the exception in 2.2) and try/catch does not work.

After step 3.) there are many other steps. How can I let the program flow around this timeout. It is timeouting when the element is not there.

Code

    def getByClass(InputElement, driver):
        getByClass = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, InputElement)))
        return getByClass

    try:
        element = Dom.getByClass('test-class', driver).text
    except TimeoutException:
        element = 'element not found'
    print(element)

Result

    except TimeoutException:
    NameError: name 'TimeoutException' is not defined
2 Answers

I can't see your import statements from your sample, so make sure you have

from selenium.common.exceptions import TimeoutException at the top of your .py file.

Import the TimeoutException from selenium exceptions like this:

from selenium.common.exceptions import TimeoutException

Put the Function inside the try block itself:

try:
    getByClass = WebDriverWait(driver, timeout).until(EC.visibility_of_element_located((By.CLASS_NAME, InputElement)))
    element = Dom.getByClass('test-class', driver).text
except TimeoutException:
    element = 'element not found'
print(element)
Related