简体   繁体   中英

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 ie the first line of the code.

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

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:
    while True:
        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
            break
        finally: 
            #code to run regardless

You need try/except statement there.

try:
  elem.click()
except Exception: # you need to find out which exception type is raised
  pass
  # do somthing else ... 

generic way to handle exception in python is

try:
    1/0
except Exception, e:
    print e

So in your case it would give

try:
    elem = browser.find_element_by_xpath(".//label[@class =     'checkbox' and contains(.,'Últimos 15 días')]/input")

except Exception, e:
    elem = browser.find_element_by_xpath

if ( elem.is_selected() ):
    print "already selected"
else:
    elem.click()

It is better to use the more specific exception type. If you use the generic Exception class, you might catch other exception where you want a different handling

Look at try and except

while elem == None:
    try:
        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()
    except Exception, e:
        elem = None

Obviously using the specific exception that is raised from the click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM