如何在python中进行异常处理?

时间:2016-08-21 01:44:38

标签: python python-2.7 exception-handling

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()

在我的代码elem.click()中,有时会出现错误。如果是,我需要再次呼叫elem = browser.find_element_by_xpath,即代码的第一行。

有没有办法在python中使用异常处理来实现这一点。 将非常感谢帮助。

4 个答案:

答案 0 :(得分:2)

据我所知,这可以通过异常处理来完成。 你可以尝试以下方法:

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

答案 1 :(得分:0)

你需要尝试/ except语句。

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

答案 2 :(得分:0)

在python中处理异常的通用方法是

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

所以在你的情况下它会给出

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()

最好使用更具体的异常类型。如果使用通用Exception类,则可能会捕获其他需要不同处理的异常

答案 3 :(得分:0)

查看tryexcept

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

显然使用点击引发的特定异常。