You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何一次性发送100个HTTP请求?现有串行代码效率低求优化

批量HTTP请求优化方案

方案一:线程池并发(基于requests,改动最小)

利用Python标准库的concurrent.futures.ThreadPoolExecutor实现并发请求,无需更换HTTP库,适合快速改造现有代码。

import requests as r
from concurrent.futures import ThreadPoolExecutor, as_completed

def send_single_request(key):
    try:
        data = {'secret_id': key}
        response = r.post('https://myurl.com', data=data)
        return f"{key} | {response.json()['message']}"
    except Exception as e:
        return f"{key} | 请求失败: {str(e)}"

if __name__ == '__main__':
    # 读取密钥列表
    with open('exmp.txt', 'r+', encoding='utf-8') as f:
        secret_keys = f.read().splitlines()
    
    # 初始化线程池,设置最大并发数为100
    with ThreadPoolExecutor(max_workers=100) as executor:
        # 提交所有请求任务
        task_futures = [executor.submit(send_single_request, key) for key in secret_keys]
        
        # 遍历已完成的任务,输出结果(结果顺序与请求发起顺序无关)
        for future in as_completed(task_futures):
            print(future.result())

如果需要保持输出顺序与原文件中密钥的顺序一致,可替换为executor.map:

# 替换as_completed部分
for result in executor.map(send_single_request, secret_keys):
    print(result)

方案二:异步IO(基于aiohttp,性能最优)

异步IO是单线程内的非阻塞并发,开销远低于线程池,适合大规模请求场景。需要先安装依赖:pip install aiohttp

import aiohttp
import asyncio

async def send_single_request(session, key):
    try:
        data = {'secret_id': key}
        async with session.post('https://myurl.com', data=data) as response:
            response_data = await response.json()
            return f"{key} | {response_data['message']}"
    except Exception as e:
        return f"{key} | 请求失败: {str(e)}"

async def main():
    # 读取密钥列表
    with open('exmp.txt', 'r+', encoding='utf-8') as f:
        secret_keys = f.read().splitlines()
    
    # 创建异步会话,限制并发连接数为100
    connector = aiohttp.TCPConnector(limit=100)
    async with aiohttp.ClientSession(connector=connector) as session:
        # 创建所有异步任务
        tasks = [send_single_request(session, key) for key in secret_keys]
        
        # 等待所有任务完成,按原顺序返回结果
        results = await asyncio.gather(*tasks)
        for result in results:
            print(result)

if __name__ == '__main__':
    asyncio.run(main())

注意事项

  • 并发数设置:100是较为稳妥的数值,若目标服务器性能有限,可适当降低,避免触发反爬或被拒绝服务。
  • 异常处理:原代码的except: pass会吞掉所有异常,优化后的代码保留了异常信息,便于排查请求失败原因。
  • 额外优化:可添加请求头(如User-Agent)、设置超时时间(例如timeout=aiohttp.ClientTimeout(total=10)),提升请求稳定性。

内容的提问来源于stack exchange,提问作者user19794652

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:10:29