网络请求不可避免会遇上请求超时的情况,在 requests 中,如果不设置你的程序可能会永远失去响应。
超时又可分为连接超时和读取超时。
连接超时
连接超时指的是在你的客户端实现到远端机器端口的连接时(对应的是connect()),Request 等待的秒数。
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秒)。
读取超时
读取超时指的就是客户端等待服务器发送请求的时间。(特定地,它指的是客户端要等待服务器发送字节之间的时间。在 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 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':&n
