异常处理

问题描述:

我试图编写一个while循环来检查自动登录过程中的错误。我希望它通过登录运行,如果出现错误,请刷新页面并重新开始。当我尝试使用例外InvalidSelectorException:时,出现未定义的错误。还有另外一种方法我应该写这个吗?或者我应该使用一个不同的例外?异常处理

while True: 
    try: 
     loginButton = browser.find_element_by_xpath('//*[@id="global-header"]/div[2]/ul/li[2]/a') 
     loginButton.click() 
     time.sleep(3) 

     iframe = browser.switch_to.frame('disneyid-iframe') 
     Username = browser.find_element_by_xpath('//*[@id="did-ui"]/div/div/section/section/form/section/') 
     Username.send_keys(usernameStr) 
     time.sleep(3) 


     password = browser.find_element_by_xpath('//*[@id="did-ui"]/div/div/section/section/form/section/div[2]/div/label/span[2]/input') 
     password.send_keys(passwordStr) 
     time.sleep(3) 


     nextButton = browser.find_element_by_xpath('//*[@id="did-ui"]/div/div/section/section/form/section/div[3]/button[2]') 
     nextButton.click() 
     break 
    except: 
     browser.refresh() 

异常条款没有例外修复它。

+0

您应该显示您的导入语句用于帮助人们排查此问题。我的猜测是你没有正确导入'InvalidSelectorException'。 –

+0

@RalphCaraveo我修好了。它只是没有处理异常声明。当我给它没有例外,它工作正常。 – tin

You can also use the except statement with no exceptions defined as follows − 

try: 
    You do your operations here; 
    ...................... 
except: 
    If there is any exception, then execute this block. 
    ...................... 
else: 
    If there is no exception then execute this block.