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 相关文章推荐
合并百度影音的离线数据( with python 2.3)
Aug 04 Python
Python分析学校四六级过关情况
Nov 22 Python
python 实现判断ip连通性的方法总结
Apr 22 Python
详解pyqt5 动画在QThread线程中无法运行问题
May 05 Python
Python面向对象之继承原理与用法案例分析
Dec 31 Python
Python Des加密解密如何实现软件注册码机器码
Jan 08 Python
如何定义TensorFlow输入节点
Jan 23 Python
Python任务调度模块APScheduler使用
Apr 15 Python
解决更改AUTH_USER_MODEL后出现的问题
May 14 Python
Pytorch学习之torch用法----比较操作(Comparison Ops)
Jun 28 Python
python pip如何手动安装二进制包
Sep 30 Python
在前女友婚礼上,用Python破解了现场的WIFI还把名称改成了
May 28 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中的MYSQL常用函数(php下操作数据库必备)
2010/09/12 PHP
thinkPHP框架RBAC实现原理分析
2019/02/01 PHP
Alliance vs Liquid BO3 第一场2.13
2021/03/10 DOTA
asp.net和asp下ACCESS的参数化查询
2008/06/11 Javascript
jqPlot 基于jquery的画图插件
2011/04/26 Javascript
jquery滚动组件(vticker.js)实现页面动态数据的滚动效果
2013/07/03 Javascript
ExtJS4给Combobox设置列表中的默认值示例
2014/05/02 Javascript
jQuery 1.9移除了$.browser可以使用$.support来替代
2014/09/03 Javascript
js控制输入框获得和失去焦点时状态显示的方法
2015/01/30 Javascript
javascript中的正则表达式使用指南
2015/03/01 Javascript
JavaScript中实现map功能代码分享
2015/06/11 Javascript
z-blog SyntaxHighlighter 长代码无法换行解决办法(基于jquery)
2015/11/18 Javascript
Vue数据驱动模拟实现3
2017/01/11 Javascript
nodejs使用express获取get和post传值及session验证的方法
2017/11/09 NodeJs
vue中子组件传递数据给父组件的讲解
2019/01/27 Javascript
VuePress 静态网站生成方法步骤
2019/02/14 Javascript
微信小程序渲染性能调优小结
2019/07/30 Javascript
javascript 原型与原型链的理解及实例分析
2019/11/23 Javascript
vue.js iview打包上线后字体图标不显示解决办法
2020/01/20 Javascript
[02:08:58]2014 DOTA2国际邀请赛中国区预选赛 Ne VS CIS
2014/05/22 DOTA
[17:00]DOTA2 HEROS教学视频教你分分钟做大人-帕克
2014/06/10 DOTA
[01:32]DOTA2次级联赛——首支职业女子战队选拔赛全记录
2014/10/23 DOTA
python Matplotlib画图之调整字体大小的示例
2017/11/20 Python
python实现TF-IDF算法解析
2018/01/02 Python
Python基于多线程实现ping扫描功能示例
2018/07/23 Python
windows下python安装小白入门教程
2018/09/18 Python
Python+OpenCV 实现图片无损旋转90°且无黑边
2019/12/12 Python
Python安装与卸载流程详细步骤(图解)
2020/02/20 Python
Python GUI库PyQt5样式QSS子控件介绍
2020/02/25 Python
Python3交互式shell ipython3安装及使用详解
2020/07/11 Python
Python爬虫进阶之爬取某视频并下载的实现
2020/12/08 Python
纯CSS3实现鼠标悬停提示气泡效果
2014/02/28 HTML / CSS
澳大利亚首个在线预订旅游网站:Wotif
2017/07/19 全球购物
幼儿园元旦家长感言
2014/02/27 职场文书
珍惜资源保护环境的建议书
2014/05/14 职场文书
《惊弓之鸟》教学反思
2016/02/20 职场文书