Python grequests模块使用场景及代码实例
作者:Yi_warmth 发布时间:2021-08-05 18:30:41
标签:Python,grequests,模块
使用场景:
1) 爬虫设置ip代理池时验证ip是否有效
2)进行压测时,进行批量请求等等场景
grequests 利用 requests和gevent库,做了一个简单封装,使用起来非常方便。
grequests.map(requests, stream=False, size=None, exception_handler=None, gtimeout=None)
另外,由于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)
来源:https://www.cnblogs.com/zhouzetian/p/13380537.html


猜你喜欢
- 本文实例讲述了Python通过递归遍历出集合中所有元素的方法。分享给大家供大家参考。具体实现方法如下:''''
- 这段时间服务器崩溃2次,一直没有找到原因,今天看到论坛发出的错误信息邮件,想起可能是mysql的默认连接数引起的问题,一查果然,老天,默认
- 在平时的工作中,难免需要一些 小Tip 来解决工作中遇到的问题,今天的文章给大家安利一个方便快捷的小技巧,将 Office(doc/docx
- 近期,我做了一个娱乐门户的投票系统,也是被刷票搞的焦头烂额,一切可用的方法都用了。但都不是太理想,最终,琢磨出来了下面的方法,我做成了流程图
- Git 服务器搭建上一章节中我们远程仓库使用了 Github,Github 公开的项目是免费的,但是如果你不想让其他人看到你的项目就需要收费
- 数学函数 1.绝对值 S:select abs(-1) value O:select abs(-1) value from dual 2.取
- .tkintertkinter是Python下面向tk的图形界面接口库,可以方便地进行图形界面设计和交互操作编程。tkinter的优点是简单
- 本文实例讲述了PHP实现数组根据某个字段进行水平合并,横向合并。分享给大家供大家参考,具体如下:PHP数组水平合并,横向合并,两条数据合并成
- #!/usr/bin/python import os import time im
- enum 是一组绑定到唯一常数值的符号名称,并且具备可迭代性和可比较性的特性。我们可以使用 enum 创建具有良好定义的标识符,而不是直接使
- 在使用easyUI做前端样式展示时,遇到了文件上传的问题,而且是在弹出层中提交表单,想做到不刷新页面,所以选择了使用ajaxFileUplo
- 本文为大家分享了python查看微信消息撤回的具体代码,供大家参考,具体内容如下1.安装itchatitchat是一个开源的python微信
- 在日常的工作中,我们通常会有去探测目标主机是否存活的应用场景,单个的服务器主机可以通过计算机自带的DOS命令来执行,但是业务的存在往往不是单
- 有些小伙伴跟小编讨论了python中使用多线程原理的问题,就聊到了关于python多线程的弊端问题,这点可能在使用的过程中大家会能感觉到。而
- 基于 Snapchat 的增强现实胡子挂件融合第一个项目中,我们将在检测到的脸上覆盖了一个小胡子。我们可以使用从摄像头捕获的连续视频帧,也可
- 直接to_excel会被覆盖,借助ExcelWriter可以实现写多个sheet。from openpyxl import load_wor
- 单神经元引论对于如花,大美,小明三个因素是如何影响小强这个因素的。这里用到的是多元的线性回归,比较基础from numpy import a
- 大大小小也搞过一些数据库设计,见过一些其他人的设计,看过些书,总结总结,经验谈。选表类型:大家都知道mysql的myisam表适合读操作大,
- 源码:#路飞骷髅import turtle as t#黄底帽子t.pu()t.goto(0,200)t.circle(-130,-80)t.
- 实现一个AuditLog的功能,是B/S结构专案。 每个用户可以登录系统,在程序中操作数据(添加,更新和删除)需要实现记录操作跟踪。是谁添加