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 11 Python
python里使用正则的findall函数的实例详解
Oct 19 Python
Pandas+Matplotlib 箱式图异常值分析示例
Dec 09 Python
pytorch 中的重要模块化接口nn.Module的使用
Apr 02 Python
基于Python中random.sample()的替代方案
May 23 Python
Python如何实现的二分查找算法
May 27 Python
python3的pip路径在哪
Jun 23 Python
python -v 报错问题的解决方法
Sep 15 Python
如何在scrapy中捕获并处理各种异常
Sep 28 Python
Python+uiautomator2实现自动刷抖音视频功能
Apr 29 Python
jupyter notebook保存文件默认路径更改方法汇总(亲测可以)
Jun 09 Python
Python与C++中梯度方向直方图的实现
Mar 17 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
PHP写日志的实现方法
2014/11/05 PHP
thinkphp模板的包含与渲染实例分析
2014/11/26 PHP
PHP类相关知识点实例总结
2016/09/28 PHP
PHP自定义序列化接口Serializable用法分析
2017/12/29 PHP
PHP7 mongoDB扩展使用的方法分享
2019/05/02 PHP
永不消失的title提示代码
2007/02/15 Javascript
javascript中处理时间戳为日期格式的方法
2014/01/02 Javascript
jQuery前端框架easyui使用Dialog时bug处理
2014/12/05 Javascript
深入理解Node.js的HTTP模块
2016/10/12 Javascript
微信小程序 教程之wxapp视图容器 scroll-view
2016/10/19 Javascript
Vuex之理解Store的用法
2017/04/19 Javascript
React Native实现进度条弹框的示例代码
2017/07/17 Javascript
Easyui使用Dialog行内按钮布局的实例
2017/07/27 Javascript
使用Fullpage插件快速开发整屏翻页的页面
2017/09/13 Javascript
详解使用PM2管理nodejs进程
2017/10/24 NodeJs
修改node.js默认的npm安装目录实例
2018/05/15 Javascript
详解Vue单元测试case写法
2018/05/24 Javascript
js使用Promise实现简单的Ajax缓存
2018/11/14 Javascript
分享一个vue项目“脚手架”项目的实现步骤
2019/05/26 Javascript
Vue.js+cube-ui(Scroll组件)实现类似头条效果的横向滚动导航条
2019/06/24 Javascript
[01:13:51]TNC vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
python通过exifread模块获得图片exif信息的方法
2015/03/16 Python
Python调用C语言开发的共享库方法实例
2015/03/18 Python
python中的不可变数据类型与可变数据类型详解
2018/09/16 Python
对python中词典的values值的修改或新增KEY详解
2019/01/20 Python
numpy:找到指定元素的索引示例
2019/11/26 Python
利用setuptools打包python程序的方法步骤
2020/01/18 Python
解决Python logging模块无法正常输出日志的问题
2020/02/21 Python
浅谈Python __init__.py的作用
2020/10/28 Python
MYPROTEIN澳大利亚官方网站:欧洲运动营养品牌
2019/06/26 全球购物
英文版餐饮业求职信
2013/10/18 职场文书
社区消防工作实施方案
2014/03/21 职场文书
企业理念标语
2014/06/09 职场文书
唐山大地震观后感
2015/06/05 职场文书
金正昆讲礼仪观后感
2015/06/11 职场文书
Vue过滤器(filter)实现及应用场景详解
2021/06/15 Vue.js