一 源起:

requests模块作为python爬虫方向的基础模块实际上在日常实际工作中也会涉及到,比如用requests向对方接口url发送POST请求进行推送数据,使用GET请求拉取数据。

但是这里有一个状况需要我们考虑到:那就是超时的情况如何处理,超时后重试的机制。

二 连接超时与读取超时:

超时:可分为连接超时和读取超时。

连接超时

连接超时,连接时request等待的时间(s)

importrequestsimportdatetime

url= 'http://www.google.com.hk'start=datetime.datetime.now()print('start', start)try:

html= requests.get(url, timeout=5).textprint('success')exceptrequests.exceptions.RequestException as e:print(e)

end=datetime.datetime.now()print('end', end)print('耗时: {time}'.format(time=(end -start)))#结果:#start 2019-11-28 14:19:24.249588#HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to www.google.com.hk timed out. (connect timeout=5)'))#end 2019-11-28 14:19:29.262519#耗时: 0:00:05.012931

因为 google 被墙了,所以无法连接,错误信息显示 connect timeout(连接超时)。

就算不设置timeout=5,也会有一个默认的连接超时时间(大约21秒左右)。

start 2019-11-28 15:00:36.441117HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))

end2019-11-28 15:00:57.459768耗时: 0:00:21.018651

读取超时

读取超时,客户端等待服务器发送请求的事件,特定地指要等待服务器发送字节之间的时间,在大部分情况下,是指服务器发送第一个字节之前的时间。

总而言之:

连接超时 ==> 发起请求连接到建立连接之间的最大时长

读取超时 ==> 连接成功开始到服务器返回响应之间等待的最大时长

故,如果设置超时时间/timeout,这个timeout值将会作为connect和read二者的timeout。如果分别设置,就需要传入一个元组:

r = requests.get('https://github.com', timeout=5)

r= requests.get('https://github.com', timeout=(0.5, 27))

例: 设置一个15秒的响应等待时间的请求:

importdatetimeimportrequests

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': 'xx', 'password': 'xx'})

start=datetime.datetime.now()print('start', start)

url_pw= 'http://www.heibanke.com/lesson/crawler_ex03/pw_list/'

try:

html= session.get(url_pw, timeout=(5, 10)).textprint('success')exceptrequests.exceptions.RequestException as e:print(e)

end=datetime.datetime.now()print('end', end)print('耗时: {time}'.format(time=(end -start)))#start 2019-11-28 19:32:20.589827## success## end 2019-11-28 19:32:22.590872## 耗时: 0:00:02.001045

如果设置为:timeout=(1, 0.5),错误信息中显示的是 read timeout(读取超时)

start 2019-11-28 19:36:38.503593HTTPConnectionPool(host='www.heibanke.com', port=80): Read timed out. (read timeout=0.5)

end2019-11-28 19:36:39.005271耗时: 0:00:00.501678

读取超时是没有默认值的,如果不设置,请求将一直处于等待状态,爬虫经常卡住又没有任何信息错误,原因就是因为读取超时了。

超时重试

一般超时不会立即返回,而是设置一个多次重连的机制

importrequestsimportdatetime

url= 'http://www.google.com.hk'

defgethtml(url):

i=0while i < 3:

start=datetime.datetime.now()print('start', start)try:

html= requests.get(url, timeout=5).textreturnhtmlexceptrequests.exceptions.RequestException:

i+= 1end=datetime.datetime.now()print('end', end)print('耗时: {time}'.format(time=(end -start)))if __name__ == '__main__':

gethtml(url)

其实 requests 已经有封装好的方法:

importtimeimportrequestsfrom requests.adapters importHTTPAdapter

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(r.text)exceptrequests.exceptions.RequestException as e:print(e)print(time.strftime('%Y-%m-%d %H:%M:%S'))#2019-11-28 19:48:05#HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to www.google.com.hk timed out. (connect timeout=5)'))#2019-11-28 19:48:25

max_retries为最大重试次数,重试3次,加上最初的一次请求,共4次,所以上述代码运行耗时20秒而不是15秒

python requests 代理超时_python requests 超时与重试相关推荐

  1. python requests是什么_python requests库学习

    Requests python的request库官方介绍就是让HTTP服务人类,所以从这点我们就可以知道request库是为了让我们更加方便的进行http相关的各种操作 我们学习request有什么用 ...

  2. python requests库作用_python Requests库入门

    一.Requests 库的安装 对Requests库 了解更多请移步:http://www.python-requests.org 安装操作: win平台:"以管理员身份运行" c ...

  3. Python爬虫代理ip异常和超时解决方案

    Python爬虫中的代理ip异常和超时如何解决?程序员在敲代码的过程中,一定会出现一定的错误,特别是像Python爬虫这种程序,并不能肯定每次请求都能保障稳定的返回同样的结果,例如反爬虫机制的强化,代 ...

  4. 工信部python证书多少钱_python requests SSL证书问题

    错误信息如下: requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_ser ...

  5. python绘制蚊香形_Python requests发送post请求的一些疑点

    前言 在Python爬虫中,使用requests发送请求,访问指定网站,是常见的做法.一般是发送GET请求或者POST请求,对于GET请求没有什么好说的,而发送POST请求,有很多朋友不是很清楚,主要 ...

  6. python使用代理爬虫_python爬虫requests使用代理ip

    python爬虫requests使用代理ip 一.总结 一句话总结: a.请求时,先将请求发给代理服务器,代理服务器请求目标服务器,然后目标服务器将数据传给代理服务器,代理服务器再将数据给爬虫. b. ...

  7. python全局代理_让requests不走系统 全局 代理

    做的是wifi自动验证登录脚本. 用的是Python的requests库. File "/home/c/.local/lib/python2.7/site-packages/requests ...

  8. python requests请求方式_Python Requests库使用2:请求方法

    GitHub API HTTP verbs Where possible, API v3 strives to use appropriate HTTP verbs for each action. ...

  9. python requests session刷新_Python Requests Session set-cookie不生效的坑

    我们知道 Python Requests库 中的 Session 模块有连接池和会话管理的功能,比如请求一个登录接口后,会自动处理 response 中的 set-cookie,下次再请求时会自动把 ...

最新文章

  1. Java swing实现Visio中对直线、曲线、折线的画及拖动删除
  2. spring boot 异常汇总
  3. go.js中的图标(icons)的使用
  4. java ee jsp_EE JSP:Servlet的反向外套
  5. 网格变形动画MeshTransform
  6. 1.1.0-简介-P3-CAP 分布式 高可用
  7. rsync、scp “tab” 卡顿问题
  8. Android完美适配dimens.xml脚本
  9. 初学者C语言输入输出挖坑填补处须知
  10. 精品手机看片神器电影网址导航网站
  11. R语言的画图代码及差异性分析
  12. 那些逃离北上广的人后悔吗,有过遗憾吗?
  13. 求最大公约数代码 Java_java怎么求最大公约数?
  14. k8s pod分类、核心组件、网络模型、kubectl常用命令
  15. 盘点2018年云计算热点:云原生、全栈云,云大脑,谁能独占鳌头?
  16. Python pip 修改镜像源为豆瓣源的两种方法
  17. 蔡高厅高等数学21-连续函数闭区间的性质(最大最小值定理、有界性定理、零值点定理、介值定理、推论)
  18. 贪心算法--最小耗费生成树(Prim算法)
  19. 牛客网前端刷题(一)
  20. 嵌入式linux的开发流程

热门文章

  1. 我学会了如何入侵Facebook Messenger Soccer游戏
  2. hex文件matlab处理,基于MATLAB生成Intel HEX文件
  3. Python3.x+Fiddler抓取APP数据
  4. 一张图理清 Python3 所有知识点
  5. Python3 网络爬虫:下载小说的正确姿势
  6. 仅需1秒!搞定100万行数据:超强Python数据分析利器
  7. Hive 老当益庄 | 深度解读 Flink 1.11:流批一体 Hive 数仓
  8. Git 代码管理(代码提交和代码回退)
  9. ExtJs2.0学习系列(12)--Ext.TreePanel之第一式
  10. ashx文件的几种使用