要編寫一個使用協程的Python爬蟲,你可以使用aiohttp
庫來處理異步HTTP請求,以及asyncio
庫來管理協程。以下是一個簡單的示例,展示了如何使用這些庫來編寫一個異步爬蟲:
首先,確保安裝了aiohttp
庫:
pip install aiohttp
然后,創建一個名為async_crawler.py
的文件,并添加以下代碼:
import asyncio
import aiohttp
from bs4 import BeautifulSoup
async def fetch(url, session):
async with session.get(url) as response:
return await response.text()
async def parse(html):
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
href = link.get('href')
print(href)
async def main():
urls = [
'https://example.com',
'https://example.org',
'https://example.net',
]
async with aiohttp.ClientSession() as session:
tasks = []
for url in urls:
task = asyncio.ensure_future(fetch(url, session))
tasks.append(task)
htmls = await asyncio.gather(*tasks)
for html in htmls:
await parse(html)
if __name__ == '__main__':
asyncio.run(main())
在這個示例中,我們定義了三個異步函數:
fetch(url, session)
:使用aiohttp
庫異步獲取指定URL的HTML內容。parse(html)
:使用BeautifulSoup
庫解析HTML內容,并打印所有鏈接的URL。main()
:創建一個aiohttp.ClientSession
,并為每個URL創建一個fetch
任務。然后,使用asyncio.gather
并發執行這些任務,并在完成后遍歷結果并調用parse
函數。要運行此爬蟲,請在命令行中執行以下命令:
python async_crawler.py
請注意,這個示例僅用于演示目的,實際應用中可能需要處理更復雜的情況,例如限制并發請求數、處理相對URL、設置請求頭等。