将传统多线程爬虫重构为 asyncio 架构的核心在于用异步协程替换阻塞的 i/o 操作,并使用 aiohttp 库处理网络请求。具体做法是引入 asyncio.semaphore 控制并发度,利用 async/await 语法实现非阻塞等待,从而在单线程内通过事件循环高效调度大量任务。

如何管理高并发下的连接数以避免资源耗尽?
使用 asyncio.Semaphore 可以精确限制同时发起的请求数量,防止因并发过高导致目标服务器拒绝服务或本地内存溢出。在代码中实例化一个信号量对象,并在每个协程执行请求前调用 acquire(),请求结束后在 finally 块中调用 release(),确保即使发生异常也能释放锁。

import asyncio
import aiohttp
async def fetch(session, url, semaphore):
async with semaphore:
print(f"Fetching {url}")
async with session.get(url) as response:
return await response.text()
async def main():
semaphore = asyncio.Semaphore(50)
connector = aiohttp.TCPConnector(limit=50)
async with aiohttp.ClientSession(connector=connector) as session:
tasks = [fetch(session, f"https://example.com/page/{i}", semaphore) for i in range(100)]
results = await asyncio.gather(*tasks)
print(f"Total results: {len(results)}")
asyncio.run(main())
上述代码中,Semaphore(50) 限制了最大并发数为 50。TCPConnector(limit=50) 进一步在底层连接池层面限制了连接数。运行该程序将依次抓取 100 个页面,但同一时刻只有 50 个请求处于活跃状态,其余请求在队列中等待。
如何处理单个请求失败而不中断整个任务组?
在 asyncio.gather 中设置 return_exceptions=True 参数,可以将异常作为普通结果返回,而不是直接抛出中断程序。结合 try-except 块捕获特定异常(如 aiohttp.ClientError),可以对失败请求进行重试或记录日志,确保其他成功请求的结果依然被收集和处理。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。

import asyncio
import aiohttp
async def safe_fetch(session, url):
try:
async with session.get(url) as response:
response.raise_for_status()
return await response.text()
except aiohttp.ClientError as e:
print(f"Failed to fetch {url}: {e}")
return None
async def main():
urls = ["https://example.com/valid", "https://example.com/invalid"]
async with aiohttp.ClientSession() as session:
tasks = [safe_fetch(session, url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
for res in results:
if isinstance(res, Exception):
print(f"Exception occurred: {res}")
elif res is not None:
print(f"Success: {len(res)} chars")
else:
print("Handled failure")
asyncio.run(main())
该示例展示了当访问无效 URL 时,safe_fetch 捕获异常并返回 None,而 main 函数中的 gather 不会崩溃,而是继续处理所有结果。开发者可以根据 results 列表中的值判断哪些请求成功,哪些失败,从而实现鲁棒的爬虫逻辑。
基于程序中某个输入、条件或结果的具体问题
当输入 URL 列表中包含大量重复域名时,aiohttp 的连接复用机制会自动优化性能,因为同一个域名的 TCP 连接会被缓存和重用。这意味着即使并发度高,实际建立的物理连接数也不会无限增长,从而减少 DNS 解析和握手开销。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










