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