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中的函数编程
Apr 13 Python
Python实现的简单hangman游戏实例
Jun 28 Python
python 计算两个日期相差多少个月实例代码
May 24 Python
python+selenium识别验证码并登录的示例代码
Dec 21 Python
批量将ppt转换为pdf的Python代码 只要27行!
Feb 26 Python
Python实现iOS自动化打包详解步骤
Oct 03 Python
python 用for循环实现1~n求和的实例
Feb 01 Python
Python一个简单的通信程序(客户端 服务器)
Mar 06 Python
python gdal安装与简单使用
Aug 01 Python
python绘制玫瑰的实现代码
Mar 02 Python
浅谈Python3多线程之间的执行顺序问题
May 02 Python
读取nii或nii.gz文件中的信息即输出图像操作
Jul 01 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
重置版游戏视频
2020/04/09 魔兽争霸
Laravel 4 初级教程之Pages、表单验证
2014/10/30 PHP
在win系统安装配置 Memcached for PHP 5.3 图文教程
2015/03/03 PHP
WordPress用户登录框密码的隐藏与部分显示技巧
2015/12/31 PHP
Zend Framework教程之Zend_Config_Xml用法分析
2016/03/23 PHP
PHP 常用时间函数资料整理
2016/10/22 PHP
php 微信开发获取用户信息如何实现
2016/12/13 PHP
window.onload 加载完毕的问题及解决方案(下)
2009/07/09 Javascript
Javascript玩转继承(三)
2014/05/08 Javascript
动态加载js的方法汇总
2015/02/13 Javascript
使用Raygun来自动追踪AngularJS中的异常
2015/06/23 Javascript
通过javascript进行UTF-8编码的实现方法
2016/06/27 Javascript
Vue监听数组变化源码解析
2017/03/09 Javascript
jQuery Masonry瀑布流布局神器使用详解
2017/05/25 jQuery
基于Vue实现拖拽功能
2020/07/29 Javascript
详解VUE-地区选择器(V-Distpicker)组件使用心得
2018/05/07 Javascript
[00:03]DOTA2新版本PA至宝展示
2014/11/19 DOTA
tornado捕获和处理404错误的方法
2014/02/26 Python
基于Python如何使用AIML搭建聊天机器人
2016/01/27 Python
shelve  用来持久化任意的Python对象实例代码
2016/10/12 Python
详解python实现读取邮件数据并下载附件的实例
2017/08/03 Python
K-近邻算法的python实现代码分享
2017/12/09 Python
tensorflow实现KNN识别MNIST
2018/03/12 Python
pandas数据分组和聚合操作方法
2018/04/11 Python
python3常用的数据清洗方法(小结)
2019/10/31 Python
Django+Celery实现动态配置定时任务的方法示例
2020/05/26 Python
英国在线购买马术服装:EQUUS
2019/07/12 全球购物
Quiksilver美国官网:始于1969年的优质冲浪服和滑雪板外套
2020/04/20 全球购物
高职助产应届生自荐信
2013/09/24 职场文书
自荐信怎么写好
2013/11/11 职场文书
青年教师个人总结
2015/02/11 职场文书
2015年音乐教研组工作总结
2015/07/22 职场文书
班主任班级管理心得体会
2016/01/07 职场文书
大学生军训心得体会5篇
2019/08/15 职场文书
详解MySQL 用户权限管理
2021/04/20 MySQL
JavaScript 防篡改对象的用法示例
2021/04/24 Javascript