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中使用md5sum检查目录中相同文件代码分享
Feb 02 Python
举例讲解Django中数据模型访问外键值的方法
Jul 21 Python
python中的文件打开与关闭操作命令介绍
Apr 26 Python
python爬虫之自动登录与验证码识别
Jun 15 Python
对Python中DataFrame选择某列值为XX的行实例详解
Jan 29 Python
VSCode中自动为Python文件添加头部注释
Nov 14 Python
pandas数据选取:df[] df.loc[] df.iloc[] df.ix[] df.at[] df.iat[]
Apr 24 Python
Eclipse配置python默认头过程图解
Apr 26 Python
python 制作python包,封装成可用模块教程
Jul 13 Python
Python基于callable函数检测对象是否可被调用
Oct 16 Python
浅谈Python实现opencv之图片色素的数值运算和逻辑运算
Jun 23 Python
 Python 中 logging 模块使用详情
Mar 03 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
ThinkPHP之A方法实例讲解
2014/06/20 PHP
php arsort 数组降序排序详细介绍
2016/11/17 PHP
基于jquery实现图片广告轮换效果代码
2011/07/07 Javascript
Javascript学习笔记 delete运算符
2011/09/13 Javascript
js页面跳转的常用方法整理
2013/10/18 Javascript
JavaScript中的关联数组问题
2015/03/04 Javascript
JavaScript 动态加载脚本和样式的方法
2015/04/13 Javascript
跟我学习javascript的prototype,getPrototypeOf和__proto__
2015/11/17 Javascript
smartupload实现文件上传时获取表单数据(推荐)
2016/12/12 Javascript
使用jQuery的load方法设计动态加载及解决被加载页面js失效问题
2017/03/01 Javascript
纯原生js实现贪吃蛇游戏
2020/04/16 Javascript
bootstrap daterangepicker汉化以及扩展功能
2017/06/15 Javascript
无限循环轮播图之运动框架(原生JS实现)
2017/10/01 Javascript
详解vue.js下引入百度地图jsApi的两种方法
2018/07/27 Javascript
vue的style绑定background-image的方式和其他变量数据的区别详解
2018/09/03 Javascript
详解JavaScript添加给定的标签选项
2018/09/17 Javascript
微信小程序加载机制及运行机制图解
2019/11/27 Javascript
vue新建项目并配置标准路由过程解析
2019/12/09 Javascript
动态规划之矩阵连乘问题Python实现方法
2017/11/27 Python
浅谈python爬虫使用Selenium模拟浏览器行为
2018/02/23 Python
深入浅析Python的类
2018/06/22 Python
python实现图片彩色转化为素描
2019/01/15 Python
Python饼状图的绘制实例
2019/01/15 Python
Django模板Templates使用方法详解
2019/07/19 Python
PyTorch中常用的激活函数的方法示例
2019/08/20 Python
详解Python中list[::-1]的几种用法
2020/11/16 Python
怎样有效的进行自我评价
2013/10/06 职场文书
写好自荐信的几个要点
2013/12/26 职场文书
幼儿园小班教学反思
2014/02/02 职场文书
幼儿园见习报告
2014/10/30 职场文书
市级三好生竞选稿
2015/11/21 职场文书
喜迎建国70周年:有关爱国的名言名句
2019/09/24 职场文书
java Nio使用NioSocket客户端与服务端交互实现方式
2021/06/15 Java/Android
Python实现照片卡通化
2021/12/06 Python
Django+Nginx+uWSGI 定时任务的实现方法
2022/01/22 Python
Echarts如何重新渲染实例详解
2022/05/30 Javascript