pythonrequesttimeout_Python:requests:详解超时和重试⽹络请求不可避免会遇上请求超时的情况,在 requests 中,如果不设置你的程序可能会永远失去响应。session如何设置和读取
超时⼜可分为连接超时和读取超时。
连接超时
连接超时指的是在你的客户端实现到远端机器端⼝的连接时(对应的是connect()),Request 等待的秒数。import time
import requests
url = 'le.hk'
print(time.strftime('%Y-%m-%d %H:%M:%S'))
try:
html = (url, timeout=5).text
print('success')
ptions.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='le.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(,
2018-12-14 14:38:25
就算不设置,也会有⼀个默认的连接超时时间(我测试了下,⼤概是21秒)。
读取超时
读取超时指的就是客户端等待服务器发送请求的时间。(特定地,它指的是客户端要等待服务器发送
字节之间的时间。在 99.9% 的情况下
这指的是服务器发送第⼀个字节之前的时间)。
简单的说,连接超时就是发起请求连接到连接建⽴之间的最⼤时长,读取超时就是连接成功开始到服务器返回响应之间等待的最⼤时长。
如果你设置了⼀个单⼀的值作为 timeout,如下所⽰:r = ('github', timeout=5)
这⼀ timeout 值将会⽤作 connect 和 read ⼆者的 timeout。如果要分别制定,就传⼊⼀个元组:
r = ('github', timeout=(3.05, 27))
⿊板课爬⾍闯关的第四关正好⽹站⼈为设置了⼀个15秒的响应等待时间,拿来做说明最好不过了。import time
import requests
url_login = 'www.heibanke/accounts/login/?next=/lesson/crawler_ex03/'
session = requests.Session()
<(url_login)
token = kies['csrftoken']
session.post(url_login, data={'csrfmiddlewaretoken': token, 'username': 'xx', 'password': 'xx'})
print(time.strftime('%Y-%m-%d %H:%M:%S'))
url_pw = 'www.heibanke/lesson/crawler_ex03/pw_list/'
try:
html = (url_pw, timeout=(5, 10)).text
print('success')
ptions.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', port=80): Read timed out. (read timeout=10)
2018-12-14 15:20:57
读取超时是没有默认值的,如果不设置,程序将⼀直处于等待状态。我们的爬⾍经常卡死⼜没有任何的报错信息,原因就在这⾥了。超时重试
⼀般超时我们不会⽴即返回,⽽会设置⼀个三次重连的机制。def gethtml(url):
i = 0
while i < 3:
try:
html = (url, timeout=5).text
return html
ptions.RequestException:
i += 1
其实 requests 已经帮我们封装好了。(但是代码好像变多了...)import time
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
print(time.strftime('%Y-%m-%d %H:%M:%S'))
try:
r = s.get('le.hk', timeout=5)
ptions.RequestException as e:
print(e)
print(time.strftime('%Y-%m-%d %H:%M:%S'))
max_retries 为最⼤重试次数,重试3次,加上最初的⼀次请求,⼀共是4次,所以上述代码运⾏耗时是20秒⽽不是15秒2018-12-14 15:34:03
HTTPConnectionPool(host='le.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(,
2018-12-14 15:34:23
相关博⽂推荐:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。