詳解Python requests 超時和重試的方法
網(wǎng)絡請求不可避免會遇上請求超時的情況,在 requests 中,如果不設置你的程序可能會永遠失去響應。
超時又可分為連接超時和讀取超時。
連接超時
連接超時指的是在你的客戶端實現(xiàn)到遠端機器端口的連接時(對應的是 connect() ),Request 等待的秒數(shù)。
import time import requests url = 'http://www.google.com.hk' print(time.strftime('%Y-%m-%d %H:%M:%S')) try: html = requests.get(url, timeout=5).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
因為 google 被墻了,所以無法連接,錯誤信息顯示 connect timeout(連接超時)。
2018-12-14 14:38:20
HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x00000000047F80F0>, 'Connection to www.google.com.hk timed out. (connect timeout=5)'))
2018-12-14 14:38:25
就算不設置,也會有一個默認的連接超時時間(我測試了下,大概是21秒)。
讀取超時
讀取超時指的就是客戶端等待服務器發(fā)送請求的時間。(特定地,它指的是客戶端要等待服務器發(fā)送字節(jié)之間的時間。在 99.9% 的情況下這指的是服務器發(fā)送第一個字節(jié)之前的時間)。
簡單的說,連接超時就是發(fā)起請求連接到連接建立之間的最大時長,讀取超時就是連接成功開始到服務器返回響應之間等待的最大時長。
讀取超時是沒有默認值的,如果不設置,程序將一直處于等待狀態(tài)。 我們的爬蟲經(jīng)常卡死又沒有任何的報錯信息,原因就在這里了。
如果你設置了一個單一的值作為 timeout,如下所示:
r = requests.get('https://github.com', timeout=5)
這一 timeout 值將會用作 connect 和 read 二者的 timeout。如果要分別制定,就傳入一個元組:
r = requests.get('https://github.com', timeout=(3.05, 27))
黑板課爬蟲闖關的第四關正好網(wǎng)站人為設置了一個15秒的響應等待時間,拿來做說明最好不過了。
import time import requests url_login = 'http://www.heibanke.com/accounts/login/?next=/lesson/crawler_ex03/' session = requests.Session() session.get(url_login) token = session.cookies['csrftoken'] session.post(url_login, data={'csrfmiddlewaretoken': token, 'username': 'guliang21', 'password': '123qwe'}) print(time.strftime('%Y-%m-%d %H:%M:%S')) url_pw = 'http://www.heibanke.com/lesson/crawler_ex03/pw_list/' try: html = session.get(url_pw, timeout=(5, 10)).text print('success') except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
錯誤信息中顯示的是 read timeout(讀取超時)。
2018-12-14 15:20:47
HTTPConnectionPool(host='www.heibanke.com', port=80): Read timed out. (read timeout=10)
2018-12-14 15:20:57
超時重試
一般超時我們不會立即返回,而會設置一個三次重連的機制。
def gethtml(url): i = 0 while i < 3: try: html = requests.get(url, timeout=5).text return html except requests.exceptions.RequestException: i += 1
其實 requests 已經(jīng)幫我們封裝好了。(但是代碼好像變多了…)
import time import requests from requests.adapters import HTTPAdapter s = requests.Session() s.mount('http://', HTTPAdapter(max_retries=3)) s.mount('https://', HTTPAdapter(max_retries=3)) print(time.strftime('%Y-%m-%d %H:%M:%S')) try: r = s.get('http://www.google.com.hk', timeout=5) return r.text except requests.exceptions.RequestException as e: print(e) print(time.strftime('%Y-%m-%d %H:%M:%S'))
max_retries 為最大重試次數(shù),重試3次,加上最初的一次請求,一共是4次,所以上述代碼運行耗時是20秒而不是15秒
2018-12-14 15:34:03
HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000000013269630>, 'Connection to www.google.com.hk timed out. (connect timeout=5)'))
2018-12-14 15:34:23
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- python中requests模塊的使用方法
- python中requests庫session對象的妙用詳解
- python采用requests庫模擬登錄和抓取數(shù)據(jù)的簡單示例
- Python使用requests發(fā)送POST請求實例代碼
- python中requests使用代理proxies方法介紹
- python?如何使用requests下載文件
- Python爬蟲庫requests獲取響應內容、響應狀態(tài)碼、響應頭
- Python3使用requests包抓取并保存網(wǎng)頁源碼的方法
- Python requests timeout的設置
- 解決Python requests 報錯方法集錦
- Python中Requests庫的實現(xiàn)示例
相關文章
python機器學習Github已達8.9Kstars模型解釋器LIME
這篇文章主要為大家介紹了Github已達8.9Kstars的最佳模型解釋器LIME的使用示例及功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11python中 chr unichr ord函數(shù)的實例詳解
這篇文章主要介紹了python中 chr unichr ord函數(shù)的實例詳解的相關資料,需要的朋友可以參考下2017-08-08python中判斷數(shù)字是否為質數(shù)的實例講解
在本篇文章里小編給大家分享了關于python中判斷數(shù)字是否為質數(shù)的實例講解內容,有興趣的朋友們可以學習下。2020-12-12ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程
這篇文章主要介紹了ansible-playbook實現(xiàn)自動部署KVM及安裝python3的詳細教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05PyTorch?Dataset與DataLoader使用超詳細講解
用于處理數(shù)據(jù)樣本的代碼可能會變得凌亂且難以維護;理想情況下,我們希望數(shù)據(jù)集代碼與模型訓練代碼解耦,以獲得更好的可讀性和模塊化。PyTorch提供的torch.utils.data.DataLoader和torch.utils.data.Dataset允許你使用預下載的數(shù)據(jù)集或自己制作的數(shù)據(jù)2022-10-10