guopengfa
发布于 2021-01-25 / 734 阅读 / 0 评论 / 0 点赞

python爬虫requests重试与超时参数设置

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)
    print('success',r.text)
except requests.exceptions.RequestException as e:
    print('fail',e)
print(time.strftime('%Y-%m-%d %H:%M:%S'))

以上可通过打印的时间看出间隔是大于15秒的,超时是设置在5秒钟的

通过s.mout参数来设置重试次数
通过timeout参数来设置超时时间


评论