網絡請求不可避免會遇上請求超時的情況,在 requests 中,如果不設置你的程序可能會永遠失去響應。
超時又可分為連接超時和讀取超時。
連接超時
連接超時指的是在你的客戶端實現到遠端機器端口的連接時(對應的是 connect() ),Request 等待的秒數。
import timeimport requestsurl = '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秒)。
讀取超時
讀取超時指的就是客戶端等待服務器發送請求的時間。(特定地,它指的是客戶端要等待服務器發送字節之間的時間。在 99.9% 的情況下這指的是服務器發送第一個字節之前的時間)。
簡單的說,連接超時就是發起請求連接到連接建立之間的最大時長,讀取超時就是連接成功開始到服務器返回響應之間等待的最大時長。
讀取超時是沒有默認值的,如果不設置,程序將一直處于等待狀態。 我們的爬蟲經常卡死又沒有任何的報錯信息,原因就在這里了。
如果你設置了一個單一的值作為 timeout,如下所示:
r = requests.get('https://github.com', timeout=5)這一 timeout 值將會用作 connect 和 read 二者的 timeout。如果要分別制定,就傳入一個元組:
r = requests.get('https://github.com', timeout=(3.05, 27))黑板課爬蟲闖關的第四關正好網站人為設置了一個15秒的響應等待時間,拿來做說明最好不過了。
import timeimport requestsurl_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(讀取超時)。
新聞熱點
疑難解答