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 30 Python
Python实现批量转换文件编码的方法
Jul 28 Python
简单讲解Python中的数字类型及基本的数学计算
Mar 11 Python
关于Python中空格字符串处理的技巧总结
Aug 10 Python
TensorFlow打印tensor值的实现方法
Jul 27 Python
对Python之gzip文件读写的方法详解
Feb 08 Python
Python3获取电脑IP、主机名、Mac地址的方法示例
Apr 11 Python
python pygame实现五子棋小游戏
Oct 26 Python
python定时任务 sched模块用法实例
Nov 04 Python
TensorFlow——Checkpoint为模型添加检查点的实例
Jan 21 Python
python使用pandas抽样训练数据中某个类别实例
Feb 28 Python
教你怎么用python实现字符串转日期
May 24 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
laravel5.6框架操作数据curd写法(查询构建器)实例分析
2020/01/26 PHP
PHP连接MySQL数据库操作代码实例解析
2020/07/11 PHP
jQuery弹出层插件简化版代码下载
2008/10/16 Javascript
25个非常棒的jQuery滑块插件和教程小结
2011/09/02 Javascript
javascript数组去重3种方法的性能测试与比较
2013/03/26 Javascript
a标签的href和onclick 的事件的区别介绍
2013/07/26 Javascript
JavaScript实现点击文字切换登录窗口的方法
2015/05/11 Javascript
JS访问SWF的函数用法实例
2015/07/01 Javascript
日常收集整理的JavaScript常用函数方法
2015/12/10 Javascript
详解vue.js的devtools安装
2017/05/26 Javascript
基于JavaScript实现无缝滚动效果
2017/07/21 Javascript
微信小程序ajax实现请求服务器数据及模版遍历数据功能示例
2017/12/15 Javascript
使用puppeteer破解极验的滑动验证码
2018/02/24 Javascript
uni-app如何实现增量更新功能
2020/01/03 Javascript
原生js实现自定义消息提示框
2020/11/19 Javascript
关于angular 8.1使用过程中的一些记录
2020/11/25 Javascript
[52:41]OG vs IG 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/20 DOTA
Python查看多台服务器进程的脚本分享
2014/06/11 Python
Python使用函数默认值实现函数静态变量的方法
2014/08/18 Python
python安装mysql-python简明笔记(ubuntu环境)
2016/06/25 Python
Python KMeans聚类问题分析
2018/02/23 Python
解决Shell执行python文件,传参空格引起的问题
2018/10/30 Python
Python爬虫文件下载图文教程
2018/12/23 Python
python 获取毫秒数,计算调用时长的方法
2019/02/20 Python
django将数组传递给前台模板的方法
2019/08/06 Python
pytorch构建多模型实例
2020/01/15 Python
使用Python项目生成所有依赖包的清单方式
2020/07/13 Python
Sublime Text3最新激活注册码分享适用2020最新版 亲测可用
2020/11/12 Python
表彰大会主持词
2014/03/26 职场文书
二年级班级文化建设方案
2014/05/10 职场文书
爱护环境卫生倡议书
2015/04/29 职场文书
基层工作经历证明
2015/06/19 职场文书
详解Nginx 工作原理
2021/03/31 Servers
js实现模拟购物商城案例
2021/05/18 Javascript
pytorch DataLoader的num_workers参数与设置大小详解
2021/05/28 Python
Mysql中的触发器定义及语法介绍
2022/06/25 MySQL