Python利用grequests轻松实现高并发爬虫
图/文:迷神
Python爬虫必备知名类库:requests基本上人人皆知了,K神编写,是Python发送接口请求简单,非常好用的一个三方库。但是requests发送请求是串行的,即阻塞的。发送完一条请求才能发送另一条请求。
为了提供效率,我们一般都要使用并发请求。当然,可以使用多线程,或者协程,gevent或者aiohttp,但是太麻烦了,而且由于python的GIL锁的原因,多线程也是伪多并发。
于是,K神基于gevent+requests编写的一个并发发送请求的库:grequests,支持python2/3
使用起来非常简单。
grequests安装方法:
安装方法:
pip install gevent grequests
项目地址:
https://github.com/spyoungtech/grequests
grequests简单使用
构造一个请求列表,使用grequests.map()并行发送,代码如下:
import grequests
req_list = [ # 请求列表,支持get post put 等多种方法
grequests.get('http://www.toutiao.com/get?a=1&b=2'),
grequests.post('http://www.toutiao.com/post', data={'a':1,'b':2}),
grequests.put('http://www.toutiao.com/post', json={'a': 1, 'b': 2}),
]
res_list = grequests.map(req_list) # 并行发送,等最后一个运行完后返回
print(res_list[0].text) # 打印第一个请求的响应文本
grequests使用比较简单,基本上和requests基本一致,剩下遍历:res_list就好
grequests和requests性能对比
我们以请求github为例:
import requests
import time
start = time.time()
res_list = [requests.get('https://github.com') for i in range(100)]
print(time.time()-start)
requests请求大约需要100秒左右,还是比较慢的
import grequests
import time
start = time.time()
req_list = [grequests.get('https://github.com') for i in range(100)]
res_list = grequests.map(req_list)
print(time.time()-start)
grequests请求大约4秒左右。。对,就是这么快,主要是grequests并行异步的请求。请求好了,之后我们就可以遍历结果,以进行匹配解析都是正常爬虫蜘蛛进行的操作流程了
for i in res_list:
print(i.text)
#这里可以自由发挥啦
有问题,可以留言,觉得不错,关注哦。