2017-08-11 57 views
0

建立意外的錯誤處理

我的網址均含有一組形式的名單後,在錯誤的項目繼續進行循環。我使用Selenium來填寫表單,然後我遍歷這些網址。即

for url in urls: 
    browser = webdriver.Chrome() 
    browser.implicitly_wait(30) 
    browser.get(url) 

    data = {} # dictionary containing variables to be inserted in the url's form 

    var1 = browser.find_element_by_id("id") 
    var1.clear() 
    var1.send_keys(data['var1']) 

    # here follow more variables to be inserted 

其中urls = [] # list containing all urls。這工作正常。


問題

時不時地,我收到一個意外的錯誤的網址之一。例如,來自該特定網址的錯誤不具有特定字段。

我調整了代碼以便能夠處理缺少該特定字段的所有url。一切安好。

但是,我需要從頭開始重新啓動循環 - 效率不高。

有沒有辦法告訴Python從導致錯誤的url重新啓動循環,而不是從列表中的第一個url?

+0

你試過'嘗試除了別的嗎? – otayeby

回答

1

而不必告訴Python從該點開始,而使用「嘗試」「除」的。這將簡單地跳過破壞你的循環的URL,並繼續直到它遍歷所有的URL。你還可以包括一個打印語句,以確定哪些網址沒有工作,然後回去吧事後

所以,

try: 
    for url in urls: 
     browser = webdriver.Chrome() 
     browser.implicitly_wait(30) 
     browser.get(url) 

     data = {} # dictionary containing variables to be inserted in the url's form 

     var1 = browser.find_element_by_id("id") 
     var1.clear() 
     var1.send_keys(data['var1']) 
except Exception as e: 
    print(url) 
    print('Exception:',e) 
    pass 
0

您可以使用whiletry/except

假設你的函數返回True

for url in urls: 
    success = False 
    while not success: 
     try: 
      data, success = your_function() 
     except: 
      success = False 

然後,你可以重新嘗試,直到成功。

其核心思想是您不需要重新啓動current for循環,但可以將函數包裝在內部while循環中。

+0

對,對不起。 – Sraw

+0

不需要道歉。只是讓你知道 ;-) –

0

您可以在代碼的異常句柄部分使用continue

for url in urls: 
    try: 
     code may have exception 
    except: 
     continue 
0

如果使用try except else,它可能是如下:

for url in urls: 
    browser = webdriver.Chrome() 
    browser.implicitly_wait(30) 
    browser.get(url) 

    data = {} # dictionary containing variables to be inserted in the url's form 

    try: 
     var1 = browser.find_element_by_id("id") 
     var1.clear() 
     var1.send_keys(data['var1']) 
    except Exception, exception: 
     print exception # will print the error but ignore the lines of the else statement 
     # or do something about the error 
    else: 
     print 'went well' 
     # here follow more variables to be inserted 
     # or continue your code 
0

我猜你正在調試你的代碼,你需要在你的代碼從錯誤輸出網址。 每個建議的tryexcept塊可用於處理錯誤。要不是你調試的目的,下面是調整

i = 0 # for first time. next time you can assign it to index of error generating url 
while i < len(urls): 
    try: 
     url = urls(i) 
     browser = webdriver.Chrome() 
     browser.implicitly_wait(30) 
     browser.get(url) 

     data = {} # dictionary containing variables to be inserted in  the url's form 

     var1 = browser.find_element_by_id("id") 
     var1.clear() 
     var1.send_keys(data['var1']) 
    except: 
     print i 
     raise 

您可以從錯誤了URL調試你的代碼,而不是從列表的開始。