【问题标题】:How to do exception handling in python?如何在python中进行异常处理?
【发布时间】:2016-08-21 01:44:38
【问题描述】:
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 中使用异常处理来实现这一点。 帮助将不胜感激。

【问题讨论】:

标签: python python-2.7 exception-handling


【解决方案1】:

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

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

【讨论】:

  • elem.click() 需要运行几次才能停止抛出异常。我该如何处理这种情况?
  • 将整个 try 块添加到 while 循环中,并且仅在成功时才将其中断,例如。 while True: try: `#command` except Exception: #error code break - 很抱歉仍然习惯于格式化 cmets
  • 我会把它添加到我的答案中
【解决方案2】:

你需要 try/except 语句。

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

【讨论】:

  • 但是 try 块不会只执行一次吗?我需要调用 elem.click() 直到它执行并且没有给出错误。
  • 你可以循环使用这段代码。你只需要为它找到好的控制流。也许重试直到达到最大重试次数。
【解决方案3】:

在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 类,您可能会捕获其他需要不同处理的异常

【讨论】:

    【解决方案4】:

    看看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
    

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

    【讨论】:

    • 编辑加入while循环,循环直到没有错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2020-05-01
    • 2021-09-27
    相关资源
    最近更新 更多