网页爬虫中:Semaphore是否统计所有异步进程还是仅上下文管理器下的?
问题
在网页爬取场景中,我使用Semaphore对象限制异步请求,同时存在另一个仅负责打印已爬取对象总数的异步进程。想确认:Semaphore会统计所有异步进程,还是仅统计其上下文管理器下的进程?
代码示例
爬取任务定义
async def __get_functions(self): some codes here... semaphore = asyncio.Semaphore(5) async with aiohttp.ClientSession() as session: tasks = [self.add_data(session, li, semaphore) for li in li_items] await asyncio.gather(*tasks)
单条数据处理逻辑
async def add_data(self, s, li, semaphore): some codes here ... async with semaphore: info = await self.__get_function_data(s, href) self.data.append({"Name": name, **info}) self.count += 1
程序启动入口
# 这里可以看到还有其他异步函数 async def __start_application(self): await asyncio.gather(self.__print_total_count(), self.__get_functions()) # 从类对象调用此方法 def start(self): asyncio.run(self.__start_application())
回答
Semaphore只会统计**进入其上下文管理器(async with semaphore:代码块)**的异步任务,不会统计所有异步进程。
具体到你的代码:
__print_total_count()这个异步进程全程没有接触semaphore的上下文,完全不受它的限制,也不会被计入Semaphore的计数中。- 只有当
add_data里的代码进入async with semaphore:时,才会占用Semaphore的许可(最多5个),退出上下文时释放许可。其他逻辑(比如self.data.append和self.count +=1)也不会占用许可。
简单说,Semaphore的作用范围严格限定在它的上下文管理器包裹的代码段内,和其他无关的异步任务完全不相关。
内容的提问来源于stack exchange,提问作者CodeX
相关产品推荐
相关产品推荐

