python requests 超时与重试
一 源起:
requests模块作为python爬虫方向的基础模块实际上在日常实际工作中也会涉及到,比如用requests向对方接口url发送POST请求进行推送数据,使用GET请求拉取数据。
但是这里有一个状况需要我们考虑到:那就是超时的情况如何处理,超时后重试的机制。
二 连接超时与读取超时:
超时:可分为连接超时和读取超时。
连接超时
连接超时,连接时request等待的时间(s)
import requests
import datetime url = 'http://www.google.com.hk'
start = datetime.datetime.now()
print('start', start)
try:
html = requests.get(url, timeout=5).text
print('success')
except requests.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(<urllib3.connection.HTTPConnection object at 0x000001D8ECB1CCC0>, '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.441117
HTTPConnectionPool(host='www.google.com.hk', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000023130B9CCC0>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',))
end 2019-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秒的响应等待时间的请求:
import datetime
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': '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)).text
print('success')
except requests.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.503593
HTTPConnectionPool(host='www.heibanke.com', port=80): Read timed out. (read timeout=0.5)
end 2019-11-28 19:36:39.005271
耗时: 0:00:00.501678
读取超时是没有默认值的,如果不设置,请求将一直处于等待状态,爬虫经常卡住又没有任何信息错误,原因就是因为读取超时了。
超时重试
一般超时不会立即返回,而是设置一个多次重连的机制
import requests
import datetime url = 'http://www.google.com.hk' def gethtml(url):
i = 0
while i < 3:
start = datetime.datetime.now()
print('start', start)
try:
html = requests.get(url, timeout=5).text
return html
except requests.exceptions.RequestException:
i += 1
end = datetime.datetime.now()
print('end', end)
print('耗时: {time}'.format(time=(end - start))) if __name__ == '__main__':
gethtml(url)
其实 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(r.text)
except requests.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(<urllib3.connection.HTTPConnection object at 0x0000019D8D88D208>, '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+request超时和重试
Python+request超时和重试 一.什么是超时? 1.连接超时 连接超时指的是没连接上,超过指定的时间内都没有连接上,这就是连接超时.(连接时间就是httpclient发送请求的地方开始到连接 ...
- python+requests 请求响应文本出错返回“登录超时”
Python+requests请求响应:"msg":"登录过时" 1.出错原代码: import requests import json#页面按条件搜索返回相 ...
- Python——Requests库的开发者接口
本文介绍 Python Requests 库的开发者接口,主要内容包括: 目录 一.主要接口 1. requests.request() 2. requests.head().get().post() ...
- Python Requests 小技巧总结
关于 Python Requests ,在使用中,总结了一些小技巧把,分享下. 1:保持请求之间的Cookies,我们可以这样做. import requests self.session = req ...
- 转载:python + requests实现的接口自动化框架详细教程
转自https://my.oschina.net/u/3041656/blog/820023 摘要: python + requests实现的接口自动化框架详细教程 前段时间由于公司测试方向的转型,由 ...
- python+requests接口自动化测试框架实例详解教程
1.首先,我们先来理一下思路. 正常的接口测试流程是什么? 脑海里的反应是不是这样的: 确定测试接口的工具 —> 配置需要的接口参数 —> 进行测试 —> 检查测试结果(有的需要数据 ...
- python+requests接口自动化测试
转自https://my.oschina.net/u/3041656/blog/820023 原来的web页面功能测试转变成接口测试,之前大多都是手工进行,利用postman和jmeter进行的接口测 ...
- Python requests快速上手
Python requests快速上手 这里参考官方文档,在ide中写了一遍,加深一下印象,定义的函数只是为了方便区分不同的请求方式 #-*-coding:utf-8-*- # Time:2017/1 ...
- Python requests介绍之接口介绍
Python requests介绍 引用官网介绍 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. Requests 允许你发送纯天然,植物饲养的 HTTP/1. ...
随机推荐
- 如何使用Microsoft的驱动程序验证程序解释无法分析的崩溃转储文件
这篇文章解释了如何使用驱动程序验证工具来分析崩溃转储文件. 使用Microsoft驱动程序验证工具 如果您曾经使用Windows的调试工具来分析崩溃转储,那么毫无疑问,您已经使用WinDbg打开了一个 ...
- expr算术运算
#!/bin/bash #expr MY_VAR1= MY_VAR2= #expr 是命令 MY_VAR3=`expr $MY_VAR1 + $MY_VAR2` MY_VAR4=`expr $MY_V ...
- JAVA基础--MySQL(二)
数据库约束 1.基础限制 ① 单一表内字节量总和不能超过65535,null 占用一个字节空间 ② varchar存储255 以内字节占用一个字节表示长度,255以上自己则占用两个字节表示长度 ③ ...
- .net web.config中配置字符串中特殊字符的处理
https://www.cnblogs.com/zzmzaizai/archive/2008/01/30/1059191.html 如果本身字符串中有特殊字符,如分号,此时就需要用单引号整体包裹起来, ...
- 投稿SCI杂志 | 如何撰写cover letter | 如何绘制illustrated abstract
现在大部分学术期刊杂志都要求提供这两样东西. 一个是面向editor的文章和研究的高度总结:一个是面向读者的高度总结,一图胜千言. 如何制作动画摘要呢? 收集素材,大部分内容在PPT里就能完成. 如何 ...
- Win7下msys64安装mingw工具链
1. 安装msys64 安装到指定目录, 例如C:\msys64 2. 命令行更新 运行msys2.exe打开命令行窗口, 执行命令 pacman -Syuu 3. 修改安装源 进入msys64/et ...
- 使用 Microsoft.Web.Administration 管理iis
How to Automate IIS 7 Configuration with .NET How to Automate IIS 7 Configuration with .NET Are you ...
- pc端常用电脑屏幕 ((响应式PC端媒体查询)电脑屏幕分辨率尺寸大全)
PC端************ 按屏幕宽度大小排序(主流的用橙色标明) 分辨率 比例 | 设备尺寸 1024*500 (8.9寸) 1024*768 (比例4:3 | 10.4寸.12.1寸.1 ...
- Vue 与 动态组件 import 的尝试
<template> <component :is='fuck' :data='data'></component> </template> <s ...
- 关于在php中变量少写了一个$和页面不断转圈的问题排查和vim的自动补全方式
php中的所有变量都是页面级的, 即任何一个页面, 最多 都只能在一个文件 : 当前页面内使用, 不存在跨 文件/ 跨页面的 作用域的变量! 因此, 即使是 $GLOBALS 这个变量, 虽然叫全局 ...