2017-02-20 37 views
1

我在for循環中有一個刮碼,但它需要幾個小時才能完成,並且當我的互聯網連接斷開時程序停止。我想(我)需要的是刮板開始時的一個條件,它告訴Python在這一點上繼續嘗試。 我試圖使用回答here如何使腳本在迭代中等待,直到重新建立Internet連接?

for w in wordlist: 

#some text processing, works fine, returns 'textresult' 

    if textresult == '___': #if there's nothing in the offline resources 
     bufferlist = list() 
     str1=str() 
     mlist=list() # I use these in scraping 

     br = mechanize.Browser() 

     tried=0 
     while True: 
      try: 
       br.open("http://the_site_to_scrape/") 

       # scraping, with several ifs. Each 'for w' iteration results with scrape_result string. 


      except (mechanize.HTTPError, mechanize.URLError) as e: 
       tried += 1 
       if isinstance(e,mechanize.HTTPError): 
        print e.code 
       else: 
        print e.reason.args 
      if tried > 4: 
        exit() 
        time.sleep(120) 
        continue 
      break 

作品,而我在網上。當連接斷開時,Python寫入403代碼並從wordlist跳過該單詞,轉到下一個並執行相同的操作。我如何告訴Python在迭代中等待連接?

編輯:如果你至少可以編寫一些必要的命令並告訴我它們應該放在我的代碼中,我會感激它,因爲我從來沒有處理異常循環。

編輯 - 解決方案我應用了Abhishek Jebaraj的改進解決方案。我只是添加了一個非常簡單的異常處理命令:

except: 
    print "connection interrupted" 
    time.sleep(30) 

此外,Jebaraj的getcode命令將引發錯誤。 r.getcode之前,我用這個:

import urllib 

r = urllib.urlopen("http: the site ") 

頂部答案this question幫助我的。

+1

檢查'狀態/ 10!= 20',並不斷重試循環。只需將所有內容放入for循環中,並在'while(retry)'循環中修改爲false的重試值爲2xx狀態 – ishaan

回答

0

寫另一個while循環,其中將繼續試圖連接到互聯網。

只有當它接收到200的狀態碼,然後你才能繼續你的程序時它纔會中斷。

有點像

retry = True 
while retry: 
    try: 
     r = br.open(//your site) 
     if r.getcode()/10==20: 
      retry = False 
    except: 
      // code to handle any exception 

// rest of your code 
+0

這是在'while True:'內寫入我的問題? 和/ /處理任何異常的代碼可以在我的問題相同? – Tag

+0

是的,它進入你的問題的while循環內,//處理的代碼是你想要的任何東西..也許你想在連續的連接錯誤期間打破它..或者你可以將它傳遞給你.. –

+0

相同的邏輯在我最近的編輯,只是使它更短一點..基於ishaans答案在評論.. –

相關問題