Python grequests模塊使用場景及代碼實例
使用場景:
1) 爬蟲設(shè)置ip代理池時驗證ip是否有效
2)進行壓測時,進行批量請求等等場景
grequests 利用 requests和gevent庫,做了一個簡單封裝,使用起來非常方便。
grequests.map(requests, stream=False, size=None, exception_handler=None, gtimeout=None)
另外,由于grequests底層使用的是requests,因此它支持
GET,OPTIONS, HEAD, POST, PUT, DELETE 等各種http method
所以以下的任務請求都是支持的
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))
實際操作中,也可以自定義返回的結(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)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python刪除Java源文件中全部注釋的實現(xiàn)方法
這篇文章主要介紹了Python刪除Java源文件中全部注釋的實現(xiàn)方法,涉及Python讀取文件、正則匹配、字符串查找、替換等相關(guān)操作技巧,需要的朋友可以參考下2017-08-08pycharm上的python虛擬環(huán)境移到離線機器上的方法步驟
本人在工作中需要在離線Windows環(huán)境中使用,本文主要介紹了pycharm上的python虛擬環(huán)境移到離線機器上的方法步驟,具有一定的參考價值,感興趣的可以了解一下2021-10-10用Python selenium實現(xiàn)淘寶搶單機器人
今天給大家?guī)淼氖顷P(guān)于Python實戰(zhàn)的相關(guān)知識,文章圍繞著用Python selenium實現(xiàn)淘寶搶單機器人展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06在python下使用tensorflow判斷是否存在文件夾的實例
今天小編就為大家分享一篇在python下使用tensorflow判斷是否存在文件夾的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06