在Python中,實現爬蟲并發處理通常使用多線程、多進程或異步編程。這里,我將向您展示如何使用asyncio
和aiohttp
庫實現異步爬蟲。
首先,確保您已經安裝了aiohttp
庫。如果沒有,請使用以下命令安裝:
pip install aiohttp
接下來,我們將創建一個簡單的異步爬蟲:
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')
titles = soup.find_all('h2', class_='title')
for title in titles:
print(title.get_text())
async def main():
urls = [
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3',
# 更多URL...
]
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
和parse
函數。fetch
函數使用aiohttp
庫異步獲取網頁內容,而parse
函數使用BeautifulSoup解析HTML并打印標題。
在main
函數中,我們創建一個URL列表,然后使用aiohttp.ClientSession
創建一個異步HTTP客戶端。接下來,我們為每個URL創建一個fetch
任務,并將其添加到任務列表中。使用asyncio.gather
并發執行所有任務,并在完成后收集結果。最后,我們將結果傳遞給parse
函數進行解析。
要運行此示例,請將urls
列表替換為您要爬取的網址,并確保目標網站允許爬蟲訪問。