在Python中,我们可以使用asyncio
库来实现Go爬虫的并发控制。以下是一个简单的示例,展示了如何使用asyncio
和aiohttp
库进行并发请求:
首先,确保已经安装了aiohttp
库:
pip install aiohttp
然后,创建一个名为async_crawler.py
的文件,并添加以下代码:
import asyncio import aiohttp async def fetch(url, session): async with session.get(url) as response: return await response.text() async def main(): urls = [ 'https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3', # 更多URL... ] concurrency_limit = 5 semaphore = asyncio.Semaphore(concurrency_limit) async with aiohttp.ClientSession() as session: tasks = [] for url in urls: task = asyncio.ensure_future(fetch_with_semaphore(url, session, semaphore)) tasks.append(task) responses = await asyncio.gather(*tasks) print(responses) async def fetch_with_semaphore(url, session, semaphore): async with semaphore: return await fetch(url, session) if __name__ == '__main__': asyncio.run(main())
在这个示例中,我们定义了一个fetch
函数,用于发送HTTP请求并获取响应内容。main
函数中,我们创建了一个URL列表,并设置了并发限制(concurrency_limit
)。我们还创建了一个信号量(semaphore
),用于控制并发请求的数量。
对于每个URL,我们创建了一个任务(task
),并使用asyncio.ensure_future
确保任务在事件循环中执行。我们将任务添加到任务列表中,然后使用asyncio.gather
等待所有任务完成。最后,我们打印收到的响应内容。
要运行此示例,请在命令行中输入以下命令:
python async_crawler.py
这个示例仅用于演示目的,实际应用中可能需要根据需求进行更多的错误处理和优化。