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构造icmp echo请求和实现网络探测器功能代码分享
Jan 10 Python
python 爬取微信文章
Jan 30 Python
Python探索之pLSA实现代码
Oct 25 Python
python奇偶行分开存储实现代码
Mar 19 Python
一些Centos Python 生产环境的部署命令(推荐)
May 07 Python
python实现顺序表的简单代码
Sep 28 Python
Python List cmp()知识点总结
Feb 18 Python
python 机器学习之支持向量机非线性回归SVR模型
Jun 26 Python
django使用django-apscheduler 实现定时任务的例子
Jul 20 Python
django创建超级用户过程解析
Sep 18 Python
Django跨域资源共享问题(推荐)
Mar 09 Python
Python3压缩和解压缩实现代码
Mar 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
生成sessionid和随机密码的例子
2006/10/09 PHP
网页游戏开发入门教程三(简单程序应用)
2009/11/02 PHP
shell脚本作为保证PHP脚本不挂掉的守护进程实例分享
2013/07/15 PHP
PHP数组操作类实例
2015/07/11 PHP
ThinkPHP中使用Ueditor富文本编辑器
2015/09/02 PHP
cakephp2.X多表联合查询join及使用分页查询的方法
2017/02/23 PHP
PHP实现基于3DES算法加密解密字符串示例
2018/08/24 PHP
ThinkPHP5.0框架结合Swoole开发实现WebSocket在线聊天案例详解
2019/04/02 PHP
JavaScript 原型链学习总结
2010/10/29 Javascript
JQuery对checkbox操作 (循环获取)
2011/05/20 Javascript
js 判断控件获得焦点的示例代码
2014/03/04 Javascript
抛弃Nginx使用nodejs做反向代理服务器
2014/07/17 NodeJs
JavaScript创建一个object对象并操作对象属性的用法
2015/03/23 Javascript
使用jQuery制作遮罩层弹出效果的极简实例分享
2016/05/12 Javascript
AngularJs Modules详解及示例代码
2016/09/01 Javascript
基于jQuery实现发送短信验证码后的倒计时功能(无视页面关闭)
2016/09/02 Javascript
JS中input表单隐藏域及其使用方法
2017/02/13 Javascript
ES6中Proxy与Reflect实现重载(overload)的方法
2017/03/30 Javascript
jQuery插件FusionCharts绘制2D双折线图效果示例【附demo源码】
2017/04/14 jQuery
解决jquery appaend元素中id绑定事件失效的问题
2017/09/12 jQuery
利用Angular2 + Ionic3开发IOS应用实例教程
2018/01/15 Javascript
Node.js readline模块与util模块的使用
2018/03/01 Javascript
Vue 使用 Mint UI 实现左滑删除效果CellSwipe
2018/04/27 Javascript
jQuery动态移除与增加onclick属性的方法详解
2018/06/07 jQuery
JS实现点击按钮可实现编辑功能
2018/07/03 Javascript
vue实现动态给id赋值,点击事件获取当前点击的元素的id操作
2020/11/09 Javascript
Vue+penlayers实现多边形绘制及展示
2020/12/24 Vue.js
详解Python中for循环的使用
2015/04/14 Python
Python写的一个简单监控系统
2015/06/19 Python
Python中实例化class的执行顺序示例详解
2018/10/14 Python
浅谈numpy生成数组的零值问题
2018/11/12 Python
PyCharm刷新项目(文件)目录的实现
2020/02/14 Python
django迁移文件migrations的实现
2020/03/31 Python
Python创建简单的神经网络实例讲解
2021/01/04 Python
员工安全生产责任书
2014/07/22 职场文书
大学生见习期满自我鉴定
2014/09/13 职场文书