异步爬虫aiohttp使用 目录一、背景二、应用场景三、备注一、背景最近有个爬虫需求页面是一个下拉框一个查询按钮但是下拉框里有大概七八百多个选项需求是要尽可能快的爬下来所有选项的数据。问了下AI给出了aiohttp来做异步并发请求之前也是没有用过所以本文记录一下aiohttp使用方法。二、应用场景因为我们这个属于一个爬虫项目框架任务的调度使用的aps管理任务通过数据库查询得到之前都是同步任务运行但这个aiohttp是异步的函数功能所以是要在任务里额外创建一个异步时间循环来运行异步任务。def task(task_idNone, station_idNone, collect_dateNone, province_codeNone): 被aps定时任务查询根据映射执行的具体任务入口 # 创建独立的事件循环 loop asyncio.new_event_loop() asyncio.set_event_loop(loop) try: results loop.run_until_complete(async_crawl_flow()) return results finally: loop.close() class Crawler: ...... _sem asyncio.Semaphore(10) # 控制并发数 async def async_crawl_flow(self): 异步主流程 1. 获取下拉列表拿到所有节点ID 2. 并发查询每个节点详情 timeout ClientTimeout(total30) # aitohttp接受的proxy跟request有区别是一个字符串 proxy_str self.proxy.get(http) or self.proxy.get(https) async with aiohttp.ClientSession( timeouttimeout, headersself.headers, cookiesself.cookie, proxyproxy_str ) as session: print(开始获取下拉列表...) node_list await self._fetch_node_list(session) if not node_list: print(未获取到节点列表流程终止) return [] print(f获取到 {len(node_list)} 个节点ID) print(开始并发查询节点详情...) results await self._fetch_all_details(session, node_list) print(f查询完成成功 {len(results)} 条) return results # # 第一步获取下拉列表 # async def _fetch_node_list(self, session: aiohttp.ClientSession) - list[dict]: 调用下拉列表接口提取所有节点ID try: async with session.post( https://xxx.com, json{} ) as resp: data await resp.json() node_list data.get(data, []) return node_list except Exception as e: print(f获取下拉列表失败: {e}) return [] # # 第二步并发查询详情 # async def _fetch_all_details(self, session: aiohttp.ClientSession, node_list: list[dict]) - dict: 查询所有节点的详情 results [] async def fetch_one_detail(node_info: dict): 查询单个节点详情 id node_info.get(id) name node_info.get(name) async with self._sem: try: async with session.post( https://xxx.com, json{ phyunitId: id, dataTime: self.collect_date, }, timeoutClientTimeout(total10), ) as resp: if resp.status 200: detail_data await resp.json() results[id] detail_data print(f节点 {name} 查询成功) else: print(f节点 {name} 返回状态码: {resp.status}) except asyncio.TimeoutError: print(f节点 {name} 超时) # 创建所有任务并发执行 tasks [fetch_one_detail(nl) for nl in node_list] await asyncio.gather(*tasks, return_exceptionsTrue) return results三、备注异步并发会同时向目标服务器发送n个请求过去注意控制好信号量一般建议在10-30之间左右有些网站会有限流、频繁请求检测等这种情况下并发的请求大部分都拿不到数据需要降低并发量、增加失败重试等机制。

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/10/5 3:18:56
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/10/5 3:42:18
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/10/5 19:39:38
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/10/5 16:06:34
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/5 5:51:09
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/10/5 5:40:36

日新闻

周新闻

月新闻