2015-02-05 26 views
0

我需要訪問一個url,如果它給了我一個HTTPError,我需要等5分鐘,然後再試一次(這適用於此特定網站)。它看起來像代碼不承認except子句,它仍然立即給我一個HTTPError(無需等待5分鐘)。即使使用「try and except」子句,仍然會收到HTTP404錯誤

import urllib2, datetime, re,os, requests 
from time import sleep 
import time 
from dateutil.relativedelta import relativedelta 
from requests.exceptions import HTTPError, ConnectionError 
from bs4 import BeautifulSoup 

try: 
     resp = requests.get(url) 


except HTTPError: 
     while True: 
       print "Wait." 
       time.sleep(305) 
      resp = requests.get(url) 


except ConnectionError: 
     while True: 
       print "Wait." 
       time.sleep(305) 
     resp = requests.get(url) 
+0

爲什麼'if err.code == 404'聲明? – GLHF

回答

0

你把這個resp = requests.get(url)try/except塊,但except之後你又把同樣的事情。如果出現錯誤,並在except後面輸入錯誤,則會再次拋出錯誤。

while True: 
    try: 
     resp = requests.get(url) 
    except HTTPError: 
     print "Wait." 
     time.sleep(305) 
     continue #pass the codes after this block 
    except ConnectionError: 
     print "Wait." 
     time.sleep(305) 
     continue #pass the codes after this block 
    else: 
     break 

基本上,直到你的網址反應正確,它會一次又一次地運行相同的事情。

+0

我刪除了if語句,但它仍然不起作用。 – Solar

+0

@Solar你可以再次嘗試if語句。沒有'while'循環 – GLHF

+0

仍然沒有運氣... – Solar

0

裏面你除了塊,你有這樣的:

resp = requests.get(url) 

這不是由一個try塊保護,所以它拋出一個錯誤。您必須稍微重新排列您的代碼:

while True: 
    try: 
     resp = requests.get(url) 

    except HTTPError: 
     print "Wait." 
     time.sleep(305)  

    except ConnectionError: 
     print "Wait." 
     time.sleep(305) 

    else: break 

現在是一個無限循環。當連接失敗時,循環繼續。成功時,循環退出。

+0

那麼如何在'if err.code'語句之後打破'while'循環?這是無限的,在你的答案中不可破解 – GLHF

+0

@howaboutNO已修復。我只是在複製代碼,因爲我在一個愚蠢的電話上。沒有意識到這個問題。 – refi64

相關問題