How to run other code when an error occurs?

Question:

I need to automatically log into the site, but sometimes a captcha pops up (not always). I have the code ready to run the captcha solving API. How can I activate it only when captcha appears? After opening the site, I have the code:

join = driver.find_element(By.XPATH, "xpath")
join.click()

And if a captcha appears instead of the "join" button, then the error "No such element: Unable to locate element" pops up.
How can I run the captcha solution code after this error and continue the normal code after solving the captcha?

Asked By: Ambamamba

||

Answers:

You can use a try except block:

try:
    join = driver.find_element(By.XPATH, "xpath")
    join.click()
except:
    # Your captcha code.

If you know your specific exception you can replace except: with except ExceptionName:

Answered By: TheShadow75
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.