安裝
pip install grequests
使用
grequests實際上就是封裝了gevent裏面的方法,然後配合requests實現異步的IO
- 所謂「異步 IO」,就是你發起一個 IO 操作,卻不用等它結束,你可以繼續做其他事情,當它結束時,你會得到通知。
import grequests, time
nowtime = time.time()
url = "https://blog.csdn.net/u011342224/article/details/{}"
detail_list = ['94603283', '79709322', '78959345', '78879633', '79414893']
# 生成一任務列表
tasks = (grequests.get(url.format(i)) for i in detail_list)
def exception_handler(request, exception):
print("request failed")
# imap 不按順序執行
gr = grequests.imap(tasks, exception_handler=exception_handler)
print([len(i.text) for i in gr], time.time() - nowtime)
使用gevent 和 request 實現異步
import gevent
import requests
from gevent import monkey
# socket發送請求以後就會進入等待狀態,gevent更改了這個機制
# socket.setblocking(False) -->發送請求後就不會等待服務器響應
monkey.patch_all() # 找到內置的socket並更改爲gevent自己的東西
def fetch_async(method, url, req_kwargs):
print(method, url, req_kwargs)
response = requests.request(method=method, url=url, **req_kwargs)
print(response.url, response.content)
# ##### 發送請求 #####
gevent.joinall([
# 這裏spawn是3個任務[實際是3個協程],每個任務都會執行fetch_async函數
gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/94603283', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/78959345', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://blog.csdn.net/u011342224/article/details/79414893', req_kwargs={}),
])