Python grequests模块使用场景及代码实例


Posted in Python onAugust 10, 2020

使用场景:

1) 爬虫设置ip代理池时验证ip是否有效

2)进行压测时,进行批量请求等等场景

grequests 利用 requests和gevent库,做了一个简单封装,使用起来非常方便。

grequests.map(requests, stream=False, size=None, exception_handler=None, gtimeout=None)

Python grequests模块使用场景及代码实例

另外,由于grequests底层使用的是requests,因此它支持

GET,OPTIONS, HEAD, POST, PUT, DELETE 等各种http method

所以以下的任务请求都是支持的

grequests.post(url, json={“name”:“zhangsan”})
grequests.delete(url)

代码如下:

import grequests

urls = [
  'http://www.baidu.com',
  'http://www.qq.com',
  'http://www.163.com',
  'http://www.zhihu.com',
  'http://www.toutiao.com',
  'http://www.douban.com'
]
rs = (grequests.get(u) for u in urls)
print(grequests.map(rs))  # [<Response [200]>, None, <Response [200]>, None, None, <Response [418]>]
def exception_handler(request, exception):
  print("Request failed")
reqs = [
  grequests.get('http://httpbin.org/delay/1', timeout=0.001),
  grequests.get('http://fakedomain/'),
  grequests.get('http://httpbin.org/status/500')
]
print(grequests.map(reqs, exception_handler=exception_handler))

实际操作中,也可以自定义返回的结果

修改grequests源码文件:

例如:

新增extract_item() 函数合修改map()函数

def extract_item(request):
  """
  提取request的内容
  :param request:
  :return:
  """
  item = dict()
  item["url"] = request.url
  item["text"] = request.response.text or ""
  item["status_code"] = request.response.status_code or 0
  return item

def map(requests, stream=False, size=None, exception_handler=None, gtimeout=None):
  """Concurrently converts a list of Requests to Responses.

  :param requests: a collection of Request objects.
  :param stream: If True, the content will not be downloaded immediately.
  :param size: Specifies the number of requests to make at a time. If None, no throttling occurs.
  :param exception_handler: Callback function, called when exception occured. Params: Request, Exception
  :param gtimeout: Gevent joinall timeout in seconds. (Note: unrelated to requests timeout)
  """
  requests = list(requests)
  pool = Pool(size) if size else None
  jobs = [send(r, pool, stream=stream) for r in requests]
  gevent.joinall(jobs, timeout=gtimeout)
  ret = []
  for request in requests:

    if request.response is not None:
      ret.append(extract_item(request))
    elif exception_handler and hasattr(request, 'exception'):
      ret.append(exception_handler(request, request.exception))
    else:
      ret.append(None)

  yield ret

可以直接调用:

import grequests
urls = [
  'http://www.baidu.com',
  'http://www.qq.com',
  'http://www.163.com',
  'http://www.zhihu.com',
  'http://www.toutiao.com',
  'http://www.douban.com'
]
rs = (grequests.get(u) for u in urls)
response_list = grequests.map(rs, gtimeout=10)
for response in next(response_list):
  print(response)

支持事件钩子

def print_url(r, *args, **kwargs):
print(r.url)

url = “http://www.baidu.com”
res = requests.get(url, hooks={“response”: print_url})
tasks = []
req = grequests.get(url, callback=print_url)
tasks.append(req)
ress = grequests.map(tasks)
print(ress)

Python grequests模块使用场景及代码实例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
详解Python的Django框架中的通用视图
May 04 Python
如何处理Python3.4 使用pymssql 乱码问题
Jan 08 Python
让python 3支持mysqldb的解决方法
Feb 14 Python
Python实现打印螺旋矩阵功能的方法
Nov 21 Python
Python实现的基于优先等级分配糖果问题算法示例
Apr 25 Python
python中使用zip函数出现错误的原因
Sep 28 Python
Python求两个圆的交点坐标或三个圆的交点坐标方法
Nov 07 Python
numpy库与pandas库axis=0,axis= 1轴的用法详解
May 27 Python
Tensorflow实现酸奶销量预测分析
Jul 19 Python
win10系统Anaconda和Pycharm的Tensorflow2.0之CPU和GPU版本安装教程
Dec 03 Python
在python中利用try..except来代替if..else的用法
Dec 19 Python
pytorch中的torch.nn.Conv2d()函数图文详解
Feb 28 Python
基于Python pyecharts实现多种图例代码解析
Aug 10 #Python
Python Celery异步任务队列使用方法解析
Aug 10 #Python
使用Python将语音转换为文本的方法
Aug 10 #Python
Python获取excel内容及相关操作代码实例
Aug 10 #Python
Python利用命名空间解析XML文档
Aug 10 #Python
Python如何定义有默认参数的函数
Aug 10 #Python
如何更换python默认编辑器的背景色
Aug 10 #Python
You might like
PHP5 安装方法
2006/10/09 PHP
MySQL中create table语句的基本语法是
2007/01/15 PHP
javascript实现 在光标处插入指定内容
2007/05/25 Javascript
jquery右下角弹出提示框示例代码
2013/10/08 Javascript
js判断客户端是iOS还是Android等移动终端的方法
2013/12/11 Javascript
JavaScript中String.prototype用法实例
2015/05/20 Javascript
js HTML5手机刮刮乐代码
2020/09/29 Javascript
动态加载css方法实现和深入解析
2017/01/18 Javascript
js图片延迟加载(Lazyload)三种实现方式
2017/03/01 Javascript
Vue.js中兄弟组件之间互相传值实例
2017/06/01 Javascript
node.js文件上传重命名以及移动位置的示例代码
2018/01/19 Javascript
nodejs中用npm初始化来创建package.json的实例讲解
2018/10/10 NodeJs
layer插件实现在弹出层中弹出一警告提示并关闭弹出层的方法
2019/09/24 Javascript
在Express中提供静态文件的实现方法
2019/10/17 Javascript
Vue-cli3项目引入Typescript的实现方法
2019/10/18 Javascript
Javascript作用域和作用域链原理解析
2020/03/03 Javascript
python实现端口转发器的方法
2015/03/13 Python
使用Python脚本将文字转换为图片的实例分享
2015/08/29 Python
Python第三方库xlrd/xlwt的安装与读写Excel表格
2017/01/21 Python
python+PyQT实现系统桌面时钟
2020/06/16 Python
Python对象与引用的介绍
2019/01/24 Python
Python静态类型检查新工具之pyright 使用指南
2019/04/26 Python
一篇文章了解Python中常见的序列化操作
2019/06/20 Python
Django中多种重定向方法使用详解
2019/07/17 Python
python绘制随机网络图形示例
2019/11/21 Python
用Python生成HTML表格的方法示例
2020/03/06 Python
Python3批量创建Crowd用户并分配组
2020/05/20 Python
Pycharm导入anaconda环境的教程图解
2020/07/31 Python
电气工程及自动化专业自荐书范文
2013/12/18 职场文书
项目申报专员岗位职责
2014/07/09 职场文书
小学国庆节活动方案策划书
2014/09/16 职场文书
党员违纪检讨书
2015/05/05 职场文书
高一军训口号
2015/12/25 职场文书
队列队形口号
2015/12/25 职场文书
python用海龟绘图写贪吃蛇游戏
2021/06/18 Python
在项目中使用redis做缓存的一些思路
2021/09/14 Redis