Python 爬蟲之GRequests異步模塊
運行環境:
系統: win10
Python版本: Python 3.6.6
GRequests是異步非阻塞的異步請求第三方包,使用了協程gevent,GRequests封裝了gevent的requests模塊。
安裝:
pip install grequests
簡單使用
# -*- coding: utf-8 -*-
# @Time : 2019/6/13 10:02
# @Author : 甄超鋒
# @Email : 4535@sohu.com
# @File : test.py
# @Software: PyCharm
import grequests
urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://fakedomain/',
'http://kennethreitz.com'
]
time1 = time.time()
exception_url = [] # 異常url存儲列表
rs = (grequests.get(u) for u in urls) # 異步url請求
# 異常捕獲方法
def exception_handler(request, exception):
print(request.url)
exception_url.append(exception_url)
print(exception)
print(rs)
# 此處map的requests參數是裝有實例化請求對象的列表,其返回值也是列表, size參數可以控制并發的數量, 不設置為 最大并發數,并發數也不能太大,怕你的機器抗不下來,最大控制到1000吧
res_list = grequests.map(rs, size=1, exception_handler=exception_handler)
print(res_list)
# 查看返回值的屬性值,我們關注的一般就是text json links url headers 等
res_text_list = [ret.text for ret in res_list if ret and ret.status_code == 200]
for res_text in res_text_list:
print(res_text)
time2 = time.time()
T = time2 - time1
print(u'use_grequests發起5個請求花費了{}秒'.format(T))
本次GRequests異步請求包就介紹到這里,喜歡請收藏,點贊,關注,謝謝
本文為張軍原創文章,轉載無需和我聯系,但請注明來自張軍的軍軍小站,個人博客http://www.dlhighland.cn
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

