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項(xiàng)目地址:https://github.com/spyoungtech/grequests
grequests簡單使用
首先構(gòu)造一個請求列表,使用grequests.map()并行發(fā)送,得到一個響應(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ā)送,等最后一個運(yùn)行完后返回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 requestsimport timestart = time.time()res_list = [requests.get(’https://github.com’) for i in range(100)]print(time.time()-start)
實(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)
際耗時約3.58s
異常處理
在批量發(fā)送請求時難免遇到某個請求url無法訪問或超時等異常,grequests.map()方法還支持自定義異常處理函數(shù),示例如下。
import grequestsdef 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)
運(yùn)行結(jié)果:
請求出錯請求出錯[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. PHP循環(huán)與分支知識點(diǎn)梳理2. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)3. 前端從瀏覽器的渲染到性能優(yōu)化4. ASP基礎(chǔ)入門第三篇(ASP腳本基礎(chǔ))5. css代碼優(yōu)化的12個技巧6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁8. 讀大數(shù)據(jù)量的XML文件的讀取問題9. 利用CSS3新特性創(chuàng)建透明邊框三角10. 解析原生JS getComputedStyle
