Python 爬蟲(chóng)性能相關(guān)總結(jié)
這里我們通過(guò)請(qǐng)求網(wǎng)頁(yè)例子來(lái)一步步理解爬蟲(chóng)性能
當(dāng)我們有一個(gè)列表存放了一些url需要我們獲取相關(guān)數(shù)據(jù),我們首先想到的是循環(huán)
簡(jiǎn)單的循環(huán)串行
這一種方法相對(duì)來(lái)說(shuō)是最慢的,因?yàn)橐粋€(gè)一個(gè)循環(huán),耗時(shí)是最長(zhǎng)的,是所有的時(shí)間總和
代碼如下:
import requests url_list = [ 'http://www.baidu.com', 'http://www.pythonsite.com', 'http://www.cnblogs.com/' ] for url in url_list: result = requests.get(url) print(result.text)
通過(guò)線程池
通過(guò)線程池的方式訪問(wèn),這樣整體的耗時(shí)是所有連接里耗時(shí)最久的那個(gè),相對(duì)循環(huán)來(lái)說(shuō)快了很多
import requests from concurrent.futures import ThreadPoolExecutor def fetch_request(url): result = requests.get(url) print(result.text) url_list = [ 'http://www.baidu.com', 'http://www.bing.com', 'http://www.cnblogs.com/' ] pool = ThreadPoolExecutor(10) for url in url_list: #去線程池中獲取一個(gè)線程,線程去執(zhí)行fetch_request方法 pool.submit(fetch_request,url) pool.shutdown(True)
線程池+回調(diào)函數(shù)
這里定義了一個(gè)回調(diào)函數(shù)callback
from concurrent.futures import ThreadPoolExecutor import requests def fetch_async(url): response = requests.get(url) return response def callback(future): print(future.result().text) url_list = [ 'http://www.baidu.com', 'http://www.bing.com', 'http://www.cnblogs.com/' ] pool = ThreadPoolExecutor(5) for url in url_list: v = pool.submit(fetch_async,url) #這里調(diào)用回調(diào)函數(shù) v.add_done_callback(callback) pool.shutdown()
通過(guò)進(jìn)程池
通過(guò)進(jìn)程池的方式訪問(wèn),同樣的也是取決于耗時(shí)最長(zhǎng)的,但是相對(duì)于線程來(lái)說(shuō),進(jìn)程需要耗費(fèi)更多的資源,同時(shí)這里是訪問(wèn)url時(shí)IO操作,所以這里線程池比進(jìn)程池更好
import requests from concurrent.futures import ProcessPoolExecutor def fetch_request(url): result = requests.get(url) print(result.text) url_list = [ 'http://www.baidu.com', 'http://www.bing.com', 'http://www.cnblogs.com/' ] pool = ProcessPoolExecutor(10) for url in url_list: #去進(jìn)程池中獲取一個(gè)線程,子進(jìn)程程去執(zhí)行fetch_request方法 pool.submit(fetch_request,url) pool.shutdown(True)
進(jìn)程池+回調(diào)函數(shù)
這種方式和線程+回調(diào)函數(shù)的效果是一樣的,相對(duì)來(lái)說(shuō)開(kāi)進(jìn)程比開(kāi)線程浪費(fèi)資源
from concurrent.futures import ProcessPoolExecutor import requests def fetch_async(url): response = requests.get(url) return response def callback(future): print(future.result().text) url_list = [ 'http://www.baidu.com', 'http://www.bing.com', 'http://www.cnblogs.com/' ] pool = ProcessPoolExecutor(5) for url in url_list: v = pool.submit(fetch_async, url) # 這里調(diào)用回調(diào)函數(shù) v.add_done_callback(callback) pool.shutdown()
主流的單線程實(shí)現(xiàn)并發(fā)的幾種方式
- asyncio
- gevent
- Twisted
- Tornado
下面分別是這四種代碼的實(shí)現(xiàn)例子:
asyncio例子1:
import asyncio
@asyncio.coroutine #通過(guò)這個(gè)裝飾器裝飾
def func1():
print('before...func1......')
# 這里必須用yield from,并且這里必須是asyncio.sleep不能是time.sleep
yield from asyncio.sleep(2)
print('end...func1......')
tasks = [func1(), func1()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
上述的效果是同時(shí)會(huì)打印兩個(gè)before的內(nèi)容,然后等待2秒打印end內(nèi)容
這里asyncio并沒(méi)有提供我們發(fā)送http請(qǐng)求的方法,但是我們可以在yield from這里構(gòu)造http請(qǐng)求的方法。
asyncio例子2:
import asyncio
@asyncio.coroutine
def fetch_async(host, url='/'):
print("----",host, url)
reader, writer = yield from asyncio.open_connection(host, 80)
#構(gòu)造請(qǐng)求頭內(nèi)容
request_header_content = """GET %s HTTP/1.0\r\nHost: %s\r\n\r\n""" % (url, host,)
request_header_content = bytes(request_header_content, encoding='utf-8')
#發(fā)送請(qǐng)求
writer.write(request_header_content)
yield from writer.drain()
text = yield from reader.read()
print(host, url, text)
writer.close()
tasks = [
fetch_async('www.cnblogs.com', '/zhaof/'),
fetch_async('dig.chouti.com', '/pic/show?nid=4073644713430508&lid=10273091')
]
loop = asyncio.get_event_loop()
results = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
asyncio + aiohttp 代碼例子:
import aiohttp
import asyncio
@asyncio.coroutine
def fetch_async(url):
print(url)
response = yield from aiohttp.request('GET', url)
print(url, response)
response.close()
tasks = [fetch_async('http://baidu.com/'), fetch_async('http://www.chouti.com/')]
event_loop = asyncio.get_event_loop()
results = event_loop.run_until_complete(asyncio.gather(*tasks))
event_loop.close()
asyncio+requests代碼例子
import asyncio import requests @asyncio.coroutine def fetch_async(func, *args): loop = asyncio.get_event_loop() future = loop.run_in_executor(None, func, *args) response = yield from future print(response.url, response.content) tasks = [ fetch_async(requests.get, 'http://www.cnblogs.com/wupeiqi/'), fetch_async(requests.get, 'http://dig.chouti.com/pic/show?nid=4073644713430508&lid=10273091') ] loop = asyncio.get_event_loop() results = loop.run_until_complete(asyncio.gather(*tasks)) loop.close()
gevent+requests代碼例子
import gevent
import requests
from gevent import monkey
monkey.patch_all()
def fetch_async(method, url, req_kwargs):
print(method, url, req_kwargs)
response = requests.request(method=method, url=url, **req_kwargs)
print(response.url, response.content)
# ##### 發(fā)送請(qǐng)求 #####
gevent.joinall([
gevent.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),
gevent.spawn(fetch_async, method='get', url='https://github.com/', req_kwargs={}),
])
# ##### 發(fā)送請(qǐng)求(協(xié)程池控制最大協(xié)程數(shù)量) #####
# from gevent.pool import Pool
# pool = Pool(None)
# gevent.joinall([
# pool.spawn(fetch_async, method='get', url='https://www.python.org/', req_kwargs={}),
# pool.spawn(fetch_async, method='get', url='https://www.yahoo.com/', req_kwargs={}),
# pool.spawn(fetch_async, method='get', url='https://www.github.com/', req_kwargs={}),
# ])
grequests代碼例子
這個(gè)是講requests+gevent進(jìn)行了封裝
import grequests
request_list = [
grequests.get('http://httpbin.org/delay/1', timeout=0.001),
grequests.get('http://fakedomain/'),
grequests.get('http://httpbin.org/status/500')
]
# ##### 執(zhí)行并獲取響應(yīng)列表 #####
# response_list = grequests.map(request_list)
# print(response_list)
# ##### 執(zhí)行并獲取響應(yīng)列表(處理異常) #####
# def exception_handler(request, exception):
# print(request,exception)
# print("Request failed")
# response_list = grequests.map(request_list, exception_handler=exception_handler)
# print(response_list)
twisted代碼例子
#getPage相當(dāng)于requets模塊,defer特殊的返回值,rector是做事件循環(huán) from twisted.web.client import getPage, defer from twisted.internet import reactor def all_done(arg): reactor.stop() def callback(contents): print(contents) deferred_list = [] url_list = ['http://www.bing.com', 'http://www.baidu.com', ] for url in url_list: deferred = getPage(bytes(url, encoding='utf8')) deferred.addCallback(callback) deferred_list.append(deferred) #這里就是進(jìn)就行一種檢測(cè),判斷所有的請(qǐng)求知否執(zhí)行完畢 dlist = defer.DeferredList(deferred_list) dlist.addBoth(all_done) reactor.run()
tornado代碼例子
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado import ioloop
def handle_response(response):
"""
處理返回值內(nèi)容(需要維護(hù)計(jì)數(shù)器,來(lái)停止IO循環(huán)),調(diào)用 ioloop.IOLoop.current().stop()
:param response:
:return:
"""
if response.error:
print("Error:", response.error)
else:
print(response.body)
def func():
url_list = [
'http://www.baidu.com',
'http://www.bing.com',
]
for url in url_list:
print(url)
http_client = AsyncHTTPClient()
http_client.fetch(HTTPRequest(url), handle_response)
ioloop.IOLoop.current().add_callback(func)
ioloop.IOLoop.current().start()
以上就是Python 爬蟲(chóng)性能相關(guān)總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Python 爬蟲(chóng)性能的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 詳解Python的爬蟲(chóng)框架 Scrapy
- Python 爬蟲(chóng)的原理
- Python爬蟲(chóng)與反爬蟲(chóng)大戰(zhàn)
- Python3爬蟲(chóng)發(fā)送請(qǐng)求的知識(shí)點(diǎn)實(shí)例
- 關(guān)于Python3爬蟲(chóng)利器Appium的安裝步驟
- Python3爬蟲(chóng)mitmproxy的安裝步驟
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之爬蟲(chóng)編寫(xiě)全記錄
- Python爬蟲(chóng)框架Scrapy安裝使用步驟
- Python爬蟲(chóng)模擬登錄帶驗(yàn)證碼網(wǎng)站
- 零基礎(chǔ)寫(xiě)python爬蟲(chóng)之使用urllib2組件抓取網(wǎng)頁(yè)內(nèi)容
相關(guān)文章
python利用json和pyecharts畫(huà)折線圖實(shí)例代碼
這篇文章主要介紹了python利用json和pyecharts畫(huà)折線圖實(shí)例,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12
opencv 實(shí)現(xiàn)特定顏色線條提取與定位操作
這篇文章主要介紹了opencv 實(shí)現(xiàn)特定顏色線條提取與定位操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-06-06
Python辦公自動(dòng)化處理的10大場(chǎng)景應(yīng)用示例
這篇文章主要為大家介紹了Python辦公自動(dòng)化處理的10大場(chǎng)景應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Python自動(dòng)化測(cè)試之異常處理機(jī)制實(shí)例詳解
為了保持自動(dòng)化測(cè)試用例的健壯性,異常的捕獲及處理,日志的記錄對(duì)掌握自動(dòng)化測(cè)試執(zhí)行情況尤為重要,下面這篇文章主要給大家介紹了關(guān)于Python自動(dòng)化測(cè)試之異常處理機(jī)制的相關(guān)資料,需要的朋友可以參考下2022-06-06
Python實(shí)現(xiàn)批量檢測(cè)ip地址連通性
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)批量檢測(cè)ip地址連通性并以json格式顯示(支持傳參單IP或者網(wǎng)段),感興趣的小伙伴可以了解下2024-04-04
Python輸出\u編碼將其轉(zhuǎn)換成中文的實(shí)例
今天小編就為大家分享一篇Python輸出\u編碼將其轉(zhuǎn)換成中文的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
Python tensorflow與pytorch的浮點(diǎn)運(yùn)算數(shù)如何計(jì)算
這篇文章主要介紹了Python tensorflow與pytorch的浮點(diǎn)運(yùn)算數(shù)如何計(jì)算,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-11-11

