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 02 Python
python中函数默认值使用注意点详解
Jun 01 Python
解决Python的str强转int时遇到的问题
Apr 09 Python
python实现验证码识别功能
Jun 07 Python
使用Python 统计高频字数的方法
Jan 31 Python
python画双y轴图像的示例代码
Jul 07 Python
使用WingPro 7 设置Python路径的方法
Jul 24 Python
python加载自定义词典实例
Dec 06 Python
使用python3批量下载rbsp数据的示例代码
Dec 20 Python
Python生成器next方法和send方法区别详解
May 30 Python
python 实现表情识别
Nov 21 Python
Python中Schedule模块使用详解 周期任务神器
Apr 19 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新增记录ID值的3种方法
2014/06/24 PHP
(jQuery,mootools,dojo)使用适合自己的编程别名命名
2010/09/14 Javascript
查看源码的工具 学习jQuery源码不错的工具
2011/12/26 Javascript
javascript unicode与GBK2312(中文)编码转换方法
2013/11/14 Javascript
javascript实现类似超链接的效果
2014/12/26 Javascript
jquery实现左右滑动菜单效果代码
2015/08/27 Javascript
jquery判断密码强度的验证代码
2020/04/22 Javascript
JavaScript基础教程——入门必看篇
2016/05/20 Javascript
JS实现太极旋转思路分析
2016/12/09 Javascript
js将字符串中的每一个单词的首字母变为大写其余均为小写
2017/01/05 Javascript
jQuery插件HighCharts绘制简单2D柱状图效果示例【附demo源码】
2017/03/21 jQuery
NodeJS创建最简单的HTTP服务器
2017/05/15 NodeJs
在原生不支持的旧环境中添加兼容的Object.keys实现方法
2017/09/11 Javascript
JS Testing Properties 判断属性是否在对象里的方法
2017/10/01 Javascript
jQuery实现的鼠标滚轮控制图片缩放功能实例
2017/10/14 jQuery
vue小白入门教程
2018/04/02 Javascript
JavaScript面向对象继承原理与实现方法分析
2018/08/09 Javascript
详解Vue项目部署遇到的问题及解决方案
2019/01/11 Javascript
JS中的防抖与节流及作用详解
2019/04/01 Javascript
Nodejs使用archiver-zip-encrypted库加密压缩文件时报错(解决方案)
2019/11/18 NodeJs
javaScript实现一个队列的方法
2020/07/14 Javascript
python队列通信:rabbitMQ的使用(实例讲解)
2017/12/22 Python
浅析Python语言自带的数据结构有哪些
2019/08/27 Python
在Python中利用pickle保存变量的实例
2019/12/30 Python
python实点云分割k-means(sklearn)详解
2020/05/28 Python
使用PyWeChatSpy自动回复微信拍一拍功能的实现代码
2020/07/02 Python
Python 代码调试技巧示例代码
2020/08/11 Python
详解CSS3伸缩布局盒模型Flex布局
2018/08/20 HTML / CSS
美国设计师精美珠宝购物网:Netaya
2016/08/28 全球购物
水果超市创业计划书
2014/01/27 职场文书
简历上的自我评价怎么写
2014/01/28 职场文书
单身联谊活动方案
2014/01/29 职场文书
应届电子商务毕业自荐书范文
2014/02/11 职场文书
个人求职自荐信范文
2014/06/20 职场文书
2014年新农村建设工作总结
2014/12/01 职场文书
解决python存数据库速度太慢的问题
2021/04/23 Python