爬蟲請求鏈接,有時候會出現請求失敗或者等待時間很長的情況,用下面的方法可以一定程度的解決這個問題
url='https://cl.xxxx.xyz/'+url try: response = requests.get(url, headers=headers,timeout=5)#超時設置為3秒 except Exception as e: for i in range(2): # 循環2次去請求網站 response = requests.get(url, headers=headers,timeout=10)#超時設置為5秒
這里有個問題,一旦超時,就會執行except內的循環,然而循環是必須會執行兩遍的
所以,需要找個方案當循環執行一遍且沒有問題的時候自動終止
改進,上篇遺留問題,第一次執行即try里的內容超時后會執行except里的內容,但except里內容又是循環多次執行,這樣會產生很多無用的重復請求
所以,在循環里面加個判斷,同時去掉循環里的timeout
步驟:1、獲取循環內請求的響應時間,如果大於指定時間,則繼續循環,如果小於指定時間則結束循環,改進后的代碼如下
url='https://cl.xxx.xyz/'+url try: response = requests.get(url, headers=headers,timeout=15)#超時設置為15秒 resptime_a = response.elapsed.total_seconds()#獲取請求響應時間 print("響應時間"+str(resptime_a)+"秒") except Exception as e: for i in range(100): # 循環2次去請求網站 response = requests.get(url, headers=headers) print("循環第"+str(i)+"次") resptime_b=response.elapsed.total_seconds() print("響應時間"+str(resptime_b)+"秒") if resptime_b < 10:#如果響應時間小於10秒,結束循環 break
這里主要用到break語句來中斷循環,具體參考https://www.cnblogs.com/becks/p/14081151.html
當然,如果引入判斷,那么try...except...即可刪除,執行循環獲取響應時間,判斷時間執行