Python 爬虫之GRequests异步模块
十分想念顺店杂可。。。
运行环境:
系统: win10
Python版本: Python 3.6.6
GRequests是异步非阻塞的异步请求第三方包,使用了协程gevent,GRequests封装了gevent的requests模块。
安装:
pip install grequests
简单使用
# -*- coding: utf-8 -*-
# @Time : 2019/6/13 10:02
# @Author : 甄超锋
# @Email : 4535@sohu.com
# @File : test.py
# @Software: PyCharm
import grequests
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://fakedomain/',
'http://kennethreitz.com'
]
time1 = time.time()
exception_url = [] # 异常url存储列表
rs = (grequests.get(u) for u in urls) # 异步url请求
# 异常捕获方法
def exception_handler(request, exception):
print(request.url)
exception_url.append(exception_url)
print(exception)
print(rs)
# 此处map的requests参数是装有实例化请求对象的列表,其返回值也是列表, size参数可以控制并发的数量, 不设置为 最大并发数,并发数也不能太大,怕你的机器抗不下来,最大控制到1000吧
res_list = grequests.map(rs, size=1, exception_handler=exception_handler)
print(res_list)
# 查看返回值的属性值,我们关注的一般就是text json links url headers 等
res_text_list = [ret.text for ret in res_list if ret and ret.status_code == 200]
for res_text in res_text_list:
print(res_text)
time2 = time.time()
T = time2 - time1
print(u'use_grequests发起5个请求花费了{}秒'.format(T))
本次GRequests异步请求包就介绍到这里,喜欢请收藏,点赞,关注,谢谢。
pythonQQ交流群:785239887