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魔法方法-属性转换和类的表示详解
Jul 22 Python
Python简单遍历字典及删除元素的方法
Sep 18 Python
python在非root权限下的安装方法
Jan 23 Python
Python Web程序部署到Ubuntu服务器上的方法
Feb 22 Python
python添加菜单图文讲解
Jun 04 Python
Python中的asyncio代码详解
Jun 10 Python
python读出当前时间精度到秒的代码
Jul 05 Python
Python DataFrame一列拆成多列以及一行拆成多行
Aug 06 Python
python修改linux中文件(文件夹)的权限属性操作
Mar 05 Python
Python如何省略括号方法详解
Mar 21 Python
使用pyecharts1.7进行简单的可视化大全
May 17 Python
Django修改app名称和数据表迁移方案实现
Sep 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
example1.php
2006/10/09 PHP
PHP 截取字符串函数整理(支持gb2312和utf-8)
2010/02/16 PHP
PHP创建XML的方法示例【基于DOMDocument类及SimpleXMLElement类】
2019/09/10 PHP
PHP与Web页面的交互示例详解二
2020/08/04 PHP
Save a File Using a File Save Dialog Box
2007/06/18 Javascript
JavaScript中的View-Model使用介绍
2011/08/11 Javascript
jquery 列表双向选择器之改进版
2013/08/09 Javascript
表单序列化与jq中的serialize使用示例
2014/02/21 Javascript
js中实现字符串和数组的相互转化详解
2016/01/24 Javascript
JS实现的跨浏览器解析XML文件实例
2016/06/21 Javascript
浅谈Node异步编程的机制
2017/10/18 Javascript
vue中的适配px2rem示例代码
2018/11/19 Javascript
详解几十行代码实现一个vue的状态管理
2019/01/28 Javascript
vue-router 中 meta的用法详解
2019/11/01 Javascript
浅谈JavaScript中等号、双等号、 三等号的区别
2020/08/06 Javascript
[02:07]2017国际邀请赛中国区预选赛直邀战队前瞻
2017/06/23 DOTA
Python中字符串对齐方法介绍
2015/05/21 Python
python opencv检测目标颜色的实例讲解
2018/04/02 Python
python的dataframe和matrix的互换方法
2018/04/11 Python
Tensorflow使用tfrecord输入数据格式
2018/06/19 Python
Python版名片管理系统
2018/11/30 Python
Python实现的对本地host127.0.0.1主机进行扫描端口功能示例
2019/02/15 Python
python浪漫表白源码
2019/04/05 Python
Python为何不能用可变对象作为默认参数的值
2019/07/01 Python
Python使用Beautiful Soup爬取豆瓣音乐排行榜过程解析
2019/08/15 Python
python 实现将小图片放到另一个较大的白色或黑色背景图片中
2019/12/12 Python
python如何求数组连续最大和的示例代码
2020/02/04 Python
pycharm如何实现跨目录调用文件
2020/02/28 Python
解决TensorFlow程序无限制占用GPU的方法
2020/06/30 Python
Python用dilb提取照片上人脸的示例
2020/10/26 Python
社区科普工作方案
2014/06/03 职场文书
2014大学班主任工作总结
2014/11/08 职场文书
2014年敬老院工作总结
2014/12/08 职场文书
党员自评材料范文
2014/12/17 职场文书
公司处罚决定书
2015/06/24 职场文书
Pyhton模块和包相关知识总结
2021/05/12 Python