How to trap Selenium error when element not found?

I’m using Python 3.11 on Windows 10 Pro in a cmd.exe window. I’m using Selenium to navigate a website, and enter info. I’m still new to exception handling.

When an element is not found I get an exception and stacktrace like the one below. I know how to find the element by constructing my own custom CSS selector.

How do I trap this exception that has a stack trace?

        GetHandleVerifier [0x00007FF789411F52+60322]
        (No symbol) [0x00007FF78938CEC9]
        (No symbol) [0x00007FF789247EBA]
        (No symbol) [0x00007FF789297676]
        (No symbol) [0x00007FF78929773C]
        (No symbol) [0x00007FF7892DE967]
        (No symbol) [0x00007FF7892BC25F]
        (No symbol) [0x00007FF7892DBC80]
        (No symbol) [0x00007FF7892BBFC3]
        (No symbol) [0x00007FF789289617]
        (No symbol) [0x00007FF78928A211]
        GetHandleVerifier [0x00007FF7897294AD+3301629]
        GetHandleVerifier [0x00007FF7897736D3+3605283]
        GetHandleVerifier [0x00007FF789769450+3563680]
        GetHandleVerifier [0x00007FF7894C4326+790390]
        (No symbol) [0x00007FF78939750F]
        (No symbol) [0x00007FF789393404]
        (No symbol) [0x00007FF789393592]
        (No symbol) [0x00007FF789382F9F]
        BaseThreadInitThunk [0x00007FFAA9C47344+20]
        RtlUserThreadStart [0x00007FFAA9F1CC91+33]


generally, a good way to catch an exception in Python is to let it run its course. For example, in the following screenshot, I have intentionally divided a number by 0. This generates a ZeroDivisionError exception.


Once the exception has been generated and made aware of, I can now then define it as part of my exception handling script, as in:

while True:

        denominator = int(input('Enter an integer value for the denominator: '))
        t = 5 / denominator

    except ZeroDivisionError:
        print('Cannot divide by zero.  Try again.')

print('Made it out!')

This make sense?

Yes it makes sense. But if you look at the error I put in my question, I don’t see an error value I can use in the Exception clause.

The first line in my error says “Stacktrace:” Is that the error I would use?

    # Do something
except Stacktrace as e: 
    print(f"Error was {e}")

You don’t get an exception starting with the word Traceback?

Ok I got another error. Here’s what I get just before the Stacktrace.

selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: 

I’ll try putting selenium.common.exceptions.ElementClickInterceptedException in the Except clause and see how it goes.


Note that you have to do a try / except pair and not just the keyword except.