EL323 EL323 - 3 months ago 10
Python Question

How to do exception handling in python?

elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input")
if ( elem.is_selected() ):
print "already selected"
else:
elem.click()


In my code
elem.click()
gets gives an error sometimes. If it does, I need to call
elem = browser.find_element_by_xpath
again i.e. the first line of the code.

Is there a way to achieve this using exception handling in python.
Help will be much appreciated.

Answer

From what i can understand this can be done with exception handling. you could try the following:

elem = browser.find_element_by_xpath(".//label[@class = 'checkbox' and contains(.,'Últimos 15 días')]/input")
if ( elem.is_selected() ):
    print "already selected"
else:
    try:
        #code to try to run that might cause an error
        elem.click() 
    except Exception:
        #code to run if it fails
        browser.find_element_by_xpath
    else:
        #code to run if it is the try is successful
    finally: 
        #code to run regardless