Python grequests模塊使用場(chǎng)景及代碼實(shí)例
使用場(chǎng)景:
1) 爬蟲(chóng)設(shè)置ip代理池時(shí)驗(yàn)證ip是否有效
2)進(jìn)行壓測(cè)時(shí),進(jìn)行批量請(qǐng)求等等場(chǎng)景
grequests 利用 requests和gevent庫(kù),做了一個(gè)簡(jiǎn)單封裝,使用起來(lái)非常方便。
grequests.map(requests, stream=False, size=None, exception_handler=None, gtimeout=None)

另外,由于grequests底層使用的是requests,因此它支持
GET,OPTIONS, HEAD, POST, PUT, DELETE 等各種http method
所以以下的任務(wù)請(qǐng)求都是支持的
grequests.post(url, json={“name”:“zhangsan”})
grequests.delete(url)
代碼如下:
import grequests
urls = [
'http://www.baidu.com',
'http://www.qq.com',
'http://www.163.com',
'http://www.zhihu.com',
'http://www.toutiao.com',
'http://www.douban.com'
]
rs = (grequests.get(u) for u in urls)
print(grequests.map(rs)) # [<Response [200]>, None, <Response [200]>, None, None, <Response [418]>]
def exception_handler(request, exception):
print("Request failed")
reqs = [
grequests.get('http://httpbin.org/delay/1', timeout=0.001),
grequests.get('http://fakedomain/'),
grequests.get('http://httpbin.org/status/500')
]
print(grequests.map(reqs, exception_handler=exception_handler))
實(shí)際操作中,也可以自定義返回的結(jié)果
修改grequests源碼文件:
例如:
新增extract_item() 函數(shù)合修改map()函數(shù)
def extract_item(request):
"""
提取request的內(nèi)容
:param request:
:return:
"""
item = dict()
item["url"] = request.url
item["text"] = request.response.text or ""
item["status_code"] = request.response.status_code or 0
return item
def map(requests, stream=False, size=None, exception_handler=None, gtimeout=None):
"""Concurrently converts a list of Requests to Responses.
:param requests: a collection of Request objects.
:param stream: If True, the content will not be downloaded immediately.
:param size: Specifies the number of requests to make at a time. If None, no throttling occurs.
:param exception_handler: Callback function, called when exception occured. Params: Request, Exception
:param gtimeout: Gevent joinall timeout in seconds. (Note: unrelated to requests timeout)
"""
requests = list(requests)
pool = Pool(size) if size else None
jobs = [send(r, pool, stream=stream) for r in requests]
gevent.joinall(jobs, timeout=gtimeout)
ret = []
for request in requests:
if request.response is not None:
ret.append(extract_item(request))
elif exception_handler and hasattr(request, 'exception'):
ret.append(exception_handler(request, request.exception))
else:
ret.append(None)
yield ret
可以直接調(diào)用:
import grequests urls = [ 'http://www.baidu.com', 'http://www.qq.com', 'http://www.163.com', 'http://www.zhihu.com', 'http://www.toutiao.com', 'http://www.douban.com' ] rs = (grequests.get(u) for u in urls) response_list = grequests.map(rs, gtimeout=10) for response in next(response_list): print(response)
支持事件鉤子
def print_url(r, *args, **kwargs):
print(r.url)
url = “http://www.baidu.com”
res = requests.get(url, hooks={“response”: print_url})
tasks = []
req = grequests.get(url, callback=print_url)
tasks.append(req)
ress = grequests.map(tasks)
print(ress)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python基于paramiko庫(kù)操作遠(yuǎn)程服務(wù)器的實(shí)現(xiàn)
本文主要介紹了使用Python的Paramiko庫(kù)來(lái)操作遠(yuǎn)程服務(wù)器,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01
Python 實(shí)現(xiàn)王者榮耀中的敏感詞過(guò)濾示例
今天小編就為大家分享一篇Python 實(shí)現(xiàn)王者榮耀中的敏感詞過(guò)濾示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
python定時(shí)任務(wù)schedule庫(kù)用法詳細(xì)講解
python中有一個(gè)輕量級(jí)的定時(shí)任務(wù)調(diào)度的庫(kù)schedule,下面這篇文章主要給大家介紹了關(guān)于python定時(shí)任務(wù)schedule庫(kù)用法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01
Python寫(xiě)一個(gè)字符串?dāng)?shù)字后綴部分的遞增函數(shù)
這篇文章主要介紹了Python寫(xiě)一個(gè)字符串?dāng)?shù)字后綴部分的遞增函數(shù),寫(xiě)函數(shù)之前需要Python處理重名字符串,添加或遞增數(shù)字字符串后綴,下面具體過(guò)程,需要的小伙伴可以參考一下2022-03-03
Python腳本實(shí)現(xiàn)datax全量同步mysql到hive
這篇文章主要和大家分享一下mysql全量同步到hive自動(dòng)生成json文件的python腳本,文中的示例代碼講解詳細(xì),有需要的小伙伴可以參加一下2024-10-10

