Padraic Cunningham
Padraic Cunningham

Reputation: 180441

How to ignore a particular exception and replace it with custom output in python

I have a script that logs me into a website, I need to hit a load more button repeatedly to get to the first thread, when I reach the end,, selenium throws an error because the load more button is not available as the start has been reached.

There are other errors that I do want to see but for this particular error I just wanted to ignore it and print "Reached initial thread". I was going to do something like:

class ReachedEndException(Exception):
        pass
try:
    do_somethong()
except ReachedEndException:
    print "Reached initial thread"

Am on on the right track or what is the best way to do this?

[EDIT] A working example as per Konstantin's answer.

try:
    while True:
        dr.find_element_by_xpath("//li[@class='more-pages']/a[1]").click()
        sleep(2)
    except NoSuchElementException:
        print "Reached Initial Thread."

Taken from the Selenium docs

Upvotes: 0

Views: 1127

Answers (1)

You are on the right track. You just need to catch the right error. remember that you can catch any error, whether it is built in, user defined, or coming from an external library. You need to figure out what error Selenium is raising and catch it.

Upvotes: 2

Related Questions