python 中try except 中如果出錯了。怎麼重新執行?

RT

我爬網頁的時候,經常會出現504.那麼怎麼讓except出現的時候等待一會重新執行try

難道要把try在except裡面再寫一遍?


用 time.sleep() 讓程序暫停, 用while讓程序循環

# -*- coding: utf8 -*-
import time
while True:
try:
# do something
pass
except Exception, e:
time.sleep(3)


import time

for times in range (50):#限個次數吧 不然就天荒地老了

try:

#do something.......

break

except Exception as e:

time.sleep(7)

print(e,重試第%s次%(times+1))


def xxx():
try:
# do something..
except HTTPError:
xxx()

這樣可以?


有兩方法,一種是加到一個列表中,改時間再爬一遍,另外一種方法是什麼都不做,None或PASS過濾掉這個網頁錯誤。

failed_list = []
try:
html = urllib2.urlopen( url )
except HTTPError:
print The page is not available, have a try at another time.
failed_list.append(url)
# dont stop scraping, keep going....

try:
html = urllib2.urlopen( url )
except HTTPError:
None # or pass
# dont stop scraping, keep going....


推薦閱讀:

TAG:Python | Python開發 |