asyncio
asyncio 是用來編寫 併發 代碼的庫,使用 async/await 語法。
asyncio 被用作多個提供高性能 Python 異步框架的基礎,包括網絡和網站服務,數據庫連接庫,分佈式任務隊列等等。
asyncio 往往是構建 IO 密集型和高層級 結構化 網絡代碼的最佳選擇。
aiohttp
aiohttp是一個爲Python提供異步HTTP 客戶端/服務端編程,基於asyncio(Python用於支持異步編程的標準庫)的異步庫。在爬蟲時提供異步網絡請求,而常用到的requests庫是同步庫,不能在異步的環境中使用。
結合asynio和aiohttp的一個基本使用:
import asyncio
import time
import aiohttp
async def get_info(url):
async with aiohttp.ClientSession() as session:
async with session.get(url,timeout=5) as resp:
if resp.status == 200:
print('good')
else:
print('no')
r = await resp.text()
if __name__ == '__main__':
start = time.time()
tasks = []
for i in range(100):
tasks.append(asyncio.ensure_future(get_info('https://www.baidu.com')))
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print('耗時',time.time()-start)
aiohttp-requests
這個庫時對aiohttp庫的網絡請求模塊的封裝,用了這個庫,在異步網絡請求的時候,可以在寫法上更簡潔易懂。本質上還是aiohttp庫的使用。推薦使用這個庫來做網絡請求。
結合asynio和aiohttp-requests 的一個基本使用(和上面的代碼效果是一樣的):
import asyncio
import time
from aiohttp_requests import requests
async def get_info(url):
resp = await requests.get(url)
if resp.status == 200: # 注意這裏是status,不是status_code
print('good')
else:
print('no')
r = await resp.text()
if __name__ == '__main__':
start = time.time()
tasks = []
for i in range(10):
tasks.append(asyncio.ensure_future(get_info('https://www.baidu.com')))
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
print('耗時',time.time()-start)
aiofiles
aiofiles是一個用Python編寫,用於處理asyncio應用程序中的本地磁盤文件。爬蟲過程中用它來進行文件的異步操作。
官方文檔中的基本用法如下:
async with aiofiles.open('filename', mode='r') as f:
contents = await f.read()
print(contents)
'My file contents'
或者:
async with aiofiles.open('filename') as f:
async for line in f:
...