Python使用grequests并發(fā)發(fā)送請求的示例
前言
requests是Python發(fā)送接口請求非常好用的一個三方庫,由K神編寫,簡單,方便上手快。但是requests發(fā)送請求是串行的,即阻塞的。發(fā)送完一條請求才能發(fā)送另一條請求。
為了提升測試效率,一般我們需要并行發(fā)送請求。這里可以使用多線程,或者協(xié)程,gevent或者aiohttp,然而使用起來,都相對麻煩。
grequests是K神基于gevent+requests編寫的一個并發(fā)發(fā)送請求的庫,使用起來非常簡單。
安裝方法: pip install gevent grequests
項目地址:https://github.com/spyoungtech/grequests
grequests簡單使用
首先構(gòu)造一個請求列表,使用grequests.map()并行發(fā)送,得到一個響應(yīng)列表。示例如下。
import grequests
req_list = [ # 請求列表
grequests.get('http://httpbin.org/get?a=1&b=2'),
grequests.post('http://httpbin.org/post', data={'a':1,'b':2}),
grequests.put('http://httpbin.org/post', json={'a': 1, 'b': 2}),
]
res_list = grequests.map(req_list) # 并行發(fā)送,等最后一個運行完后返回
print(res_list[0].text) # 打印第一個請求的響應(yīng)文本
grequests支持get、post、put、delete等requests支持的HTTP請求方法,使用參數(shù)和requests一致,發(fā)送請求非常簡單。
通過遍歷res_list可以得到所有請求的返回結(jié)果。
grequests和requests性能對比
我們可以對比下requests串行和grequests并行請求100次github.com的時間,示例如下。
使用requests發(fā)送請求
import requests
import time
start = time.time()
res_list = [requests.get('https://github.com') for i in range(100)]
print(time.time()-start)
實際耗時約100s+
使用grequests發(fā)送
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)
際耗時約3.58s
異常處理
在批量發(fā)送請求時難免遇到某個請求url無法訪問或超時等異常,grequests.map()方法還支持自定義異常處理函數(shù),示例如下。
import grequests
def err_handler(request, exception):
print("請求出錯")
req_list = [
grequests.get('http://httpbin.org/delay/1', timeout=0.001), # 超時異常
grequests.get('http://fakedomain/'), # 該域名不存在
grequests.get('http://httpbin.org/status/500') # 正常返回500的請求
]
res_list = grequests.map(reqs, exception_handler=err_handler)
print(res_list)
運行結(jié)果:
請求出錯
請求出錯
[None, None, <Response [500]>]
以上就是Python使用grequests并發(fā)發(fā)送請求的示例的詳細內(nèi)容,更多關(guān)于Python grequests發(fā)送請求的資料請關(guān)注腳本之家其它相關(guān)文章!
- python爬蟲請求庫httpx和parsel解析庫的使用測評
- python爬蟲系列網(wǎng)絡(luò)請求案例詳解
- 詳解python requests中的post請求的參數(shù)問題
- 快速一鍵生成Python爬蟲請求頭
- Python3+Django get/post請求實現(xiàn)教程詳解
- python 實現(xiàn)Requests發(fā)送帶cookies的請求
- python實現(xiàn)三種隨機請求頭方式
- Python urllib request模塊發(fā)送請求實現(xiàn)過程解析
- python 爬蟲請求模塊requests詳解
- Python Http請求json解析庫用法解析
- python 發(fā)送get請求接口詳解
- python+excel接口自動化獲取token并作為請求參數(shù)進行傳參操作
- Python爬蟲基礎(chǔ)講解之請求
相關(guān)文章
python中如何實現(xiàn)將數(shù)據(jù)分成訓(xùn)練集與測試集的方法
這篇文章主要介紹了python中如何實現(xiàn)將數(shù)據(jù)分成訓(xùn)練集與測試集的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
使用python爬蟲實現(xiàn)抓取動態(tài)加載數(shù)據(jù)
這篇文章主要給大家介紹了如何用python爬蟲抓取豆瓣電影“分類排行榜”中的電影數(shù)據(jù),比如輸入“犯罪”則會輸出所有犯罪影片的電影名稱、評分,文中通過代碼示例和圖文介紹的非常詳細,需要的朋友可以參考下2024-01-01

