在Python中,協程爬蟲可以通過使用asyncio庫和第三方庫aiohttp來處理異常。以下是一個簡單的示例,展示了如何在協程爬蟲中處理異常:
首先,確保已經安裝了aiohttp庫:
pip install aiohttp
然后,創建一個名為coroutine_crawler.py的文件,并添加以下代碼:
import asyncio
import aiohttp
from aiohttp import ClientError
async def fetch(url, session):
try:
async with session.get(url) as response:
if response.status != 200:
print(f"Error: {url} returned status {response.status}")
return None
return await response.text()
except ClientError as e:
print(f"Error: {url} - {e}")
return None
async def main():
urls = [
"https://www.example.com",
"https://www.example.org",
"https://www.example.net",
]
async with aiohttp.ClientSession() as session:
tasks = [fetch(url, session) for url in urls]
responses = await asyncio.gather(*tasks, return_exceptions=True)
for url, response in zip(urls, responses):
if isinstance(response, Exception):
print(f"Error while processing {url}: {response}")
else:
print(f"Fetched content from {url}:")
print(response[:100]) # Print the first 100 characters of the content
if __name__ == "__main__":
asyncio.run(main())
在這個示例中,我們定義了一個名為fetch的異步函數,它接受一個URL和一個aiohttp.ClientSession對象。我們使用try-except語句來捕獲可能的ClientError異常,并在發生異常時打印錯誤信息。
在main函數中,我們創建了一個aiohttp.ClientSession對象,并為給定的URL列表創建了多個fetch任務。然后,我們使用asyncio.gather函數并發執行這些任務,并設置return_exceptions=True以便在結果中包含異常。最后,我們遍歷結果并檢查每個響應是否為異常,如果是,則打印錯誤信息,否則打印響應內容的前100個字符。