Python使用grequests并發(fā)發(fā)送請求的示例
前言
requests是Python發(fā)送接口請求非常好用的一個(gè)三方庫,由K神編寫,簡單,方便上手快。但是requests發(fā)送請求是串行的,即阻塞的。發(fā)送完一條請求才能發(fā)送另一條請求。為了提升測試效率,一般我們需要并行發(fā)送請求。這里可以使用多線程,或者協(xié)程,gevent或者aiohttp,然而使用起來,都相對麻煩。
grequests是K神基于gevent+requests編寫的一個(gè)并發(fā)發(fā)送請求的庫,使用起來非常簡單。
安裝方法: pip install gevent grequests項(xiàng)目地址:https://github.com/spyoungtech/grequests
grequests簡單使用
首先構(gòu)造一個(gè)請求列表,使用grequests.map()并行發(fā)送,得到一個(gè)響應(yīng)列表。示例如下。
import grequestsreq_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ā)送,等最后一個(gè)運(yùn)行完后返回print(res_list[0].text) # 打印第一個(gè)請求的響應(yīng)文本
grequests支持get、post、put、delete等requests支持的HTTP請求方法,使用參數(shù)和requests一致,發(fā)送請求非常簡單。通過遍歷res_list可以得到所有請求的返回結(jié)果。
grequests和requests性能對比
我們可以對比下requests串行和grequests并行請求100次github.com的時(shí)間,示例如下。使用requests發(fā)送請求
import requestsimport timestart = time.time()res_list = [requests.get(’https://github.com’) for i in range(100)]print(time.time()-start)
實(shí)際耗時(shí)約100s+
使用grequests發(fā)送
import grequestsimport timestart = time.time()req_list = [grequests.get(’https://github.com’) for i in range(100)]res_list = grequests.map(req_list)print(time.time()-start)
際耗時(shí)約3.58s
異常處理
在批量發(fā)送請求時(shí)難免遇到某個(gè)請求url無法訪問或超時(shí)等異常,grequests.map()方法還支持自定義異常處理函數(shù),示例如下。
import grequestsdef err_handler(request, exception): print('請求出錯(cuò)')req_list = [ grequests.get(’http://httpbin.org/delay/1’, timeout=0.001), # 超時(shí)異常 grequests.get(’http://fakedomain/’), # 該域名不存在 grequests.get(’http://httpbin.org/status/500’) # 正常返回500的請求]res_list = grequests.map(reqs, exception_handler=err_handler)print(res_list)
運(yùn)行結(jié)果:
請求出錯(cuò)請求出錯(cuò)[None, None, <Response [500]>]
以上就是Python使用grequests并發(fā)發(fā)送請求的示例的詳細(xì)內(nèi)容,更多關(guān)于Python grequests發(fā)送請求的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 概述IE和SQL2k開發(fā)一個(gè)XML聊天程序2. XML入門精解之結(jié)構(gòu)與語法3. XML解析錯(cuò)誤:未組織好 的解決辦法4. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)5. 利用CSS3新特性創(chuàng)建透明邊框三角6. XML入門的常見問題(一)7. HTML5 Canvas繪制圖形從入門到精通8. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera9. HTML DOM setInterval和clearInterval方法案例詳解10. XML入門的常見問題(二)
