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 26 Python
分享Python字符串关键点
Dec 13 Python
在Python的一段程序中如何使用多次事件循环详解
Sep 07 Python
Python基于分水岭算法解决走迷宫游戏示例
Sep 26 Python
使用Python从零开始撸一个区块链
Mar 14 Python
详解python异步编程之asyncio(百万并发)
Jul 07 Python
Python之inspect模块实现获取加载模块路径的方法
Oct 16 Python
解决Python下json.loads()中文字符出错的问题
Dec 19 Python
基于PyQt4和PySide实现输入对话框效果
Feb 27 Python
PyQt5 QListWidget选择多项并返回的实例
Jun 17 Python
VS2019+python3.7+opencv4.1+tensorflow1.13配置详解
Apr 16 Python
Python读写csv文件流程及异常解决
Oct 20 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中实现进程间通讯
2006/10/09 PHP
wordpress之wp-settings.php
2007/08/17 PHP
php防止sql注入简单分析
2015/03/18 PHP
ThinkPHP实现更新数据实例详解(demo)
2016/06/29 PHP
网页自动跳转代码收集
2009/09/27 Javascript
jBox 2.3基于jquery的最新多功能对话框插件 常见使用问题解答
2011/11/10 Javascript
js实现上传图片预览的方法
2015/02/09 Javascript
JQuery实现动态适时改变字体颜色的方法
2015/03/10 Javascript
PHP+mysql+Highcharts生成饼状图
2015/05/04 Javascript
JavaScript中switch语句的用法详解
2015/06/03 Javascript
详解AngularJS中$filter过滤器使用(自定义过滤器)
2017/02/04 Javascript
addEventListener()与removeEventListener()解析
2017/04/20 Javascript
JS脚本实现网页自动秒杀点击
2018/01/11 Javascript
对Vue beforeRouteEnter 的next执行时机详解
2018/08/25 Javascript
详解webpack-dev-server使用方法
2018/09/14 Javascript
Vue中的Props(不可变状态)
2018/09/29 Javascript
React 实现车牌键盘的示例代码
2019/12/20 Javascript
python循环监控远程端口的方法
2015/03/14 Python
python获取时间戳的实现示例(10位和13位)
2020/09/23 Python
python实现移动木板小游戏
2020/10/09 Python
Python爬虫如何破解JS加密的Cookie
2020/11/19 Python
HTML5 Video标签的属性、方法和事件汇总介绍
2015/04/24 HTML / CSS
采用冷却技术的超自然舒适度:GhostBed床垫
2018/09/18 全球购物
JENNIFER BEHR官网:各种耳环和发饰
2020/06/07 全球购物
应用化学专业本科生求职信
2013/09/29 职场文书
大学校园毕业自我鉴定
2014/01/15 职场文书
《两只鸟蛋》教学反思
2014/02/10 职场文书
党支部公开承诺践诺书
2014/03/28 职场文书
爱国卫生月活动总结范文
2014/04/25 职场文书
2016年大学生暑期社会实践方案
2015/11/26 职场文书
Django如何与Ajax交互
2021/04/29 Python
Jupyter notebook 不自动弹出网页的解决方案
2021/05/21 Python
Python Django ORM连表正反操作技巧
2021/06/13 Python
Oracle表空间与权限的深入讲解
2021/11/17 Oracle
六个好看实用的 HTML + CSS 后台登录入口页面
2022/04/28 HTML / CSS
python使用shell脚本创建kafka连接器
2022/04/29 Python