Python requests.get运行提速的通用方法与最佳实践有哪些?
问题根因定位
你遇到的请求变慢90%以上是代码逻辑缺陷导致,和服务器拦截、文件读取效率无关,核心瓶颈是串行网络IO的等待时间被完全浪费,叠加无效重试、无超时控制的问题,越往后卡住的无效请求越多,整体速度就越慢。
现有代码的核心错误
- 每次调用
req()函数都新建一个requests.Session(),完全浪费了Session的连接复用能力,加的Connection:close头更是直接关闭了长连接,Session等于白写 - 纯串行执行请求,上一个请求完成后才会发下一个,网络IO等待时间(DNS查询、TCP握手、响应等待)全部被闲置
- 没有设置请求超时,不存在的子域名会卡住数秒甚至数十秒,积累后整体速度越来越慢
- 无效重试逻辑:子域名不存在的场景下重试10次没有任何意义,只会拉长无效等待时间
- 用HTTP请求验证子域名存在性本身就是低效方案:子域名存在不代表开放443端口,且HTTP请求的开销是DNS查询的数倍到数十倍,还容易触发目标站点限流
优化方案
基础优化(适配1k~10w级字典)
- 改用多线程/异步并发请求:网络IO是IO密集型场景,用并发可以把闲置的等待时间利用起来,性能可以提升几十倍
- 统一设置超时时间:每个请求最多等待2~3秒,超时直接判定为不存在,避免卡请求
- 去掉无效重试:子域名不存在的场景无需重试,最多重试1次即可
- 优先用DNS查询替代HTTP请求做验证:仅需查询子域名的A/AAAA记录是否存在,即可判定子域名是否有效,速度快且不会触发目标站点的HTTP限流
百万级字典适配方案
- 增加并发数控制:用信号量限制同时并发的请求数在200~500之间,避免本地端口被占满抛出连接错误
- 流式加载字典:不需要一次性把百万条数据全部读进内存,逐行读取逐行处理即可
- 增加去重逻辑:提前对字典做去重,避免重复查询相同子域名
- 支持断点续跑:记录已经查询过的子域名,程序中断后不需要从头开始跑
- 如遇目标DNS限流,可配置公共DNS池轮询查询
优化后代码示例
多线程HTTP请求版
import requests from concurrent.futures import ThreadPoolExecutor, as_completed # 并发数可根据本地网络情况调整,一般20~100都可以 MAX_WORKERS = 50 TIMEOUT = 2 c = 0 def req(test_url): global c try: # 不同子域名无法复用连接,不需要Session requests.get(f"https://{test_url}", timeout=TIMEOUT, headers={'Connection': 'close'}) return test_url, True except Exception: c += 1 return test_url, False if __name__ == "__main__": target_url = "google.com" test_urls = [] with open('subdomain1k.txt', 'r') as f: for line in f: word = line.strip() if word: test_urls.append(f"{word}.{target_url}") with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [executor.submit(req, url) for url in test_urls] for future in as_completed(futures): test_url, is_exist = future.result() if is_exist: print(test_url) # 可选写入文件 # with open('out.txt', 'a') as wf: # wf.write(f"{test_url}\n")
更高效率的DNS查询版(需要先安装pip install dnspython)
import dns.resolver from concurrent.futures import ThreadPoolExecutor, as_completed MAX_WORKERS = 100 # 配置公共DNS池,避免单个DNS限流 resolvers = dns.resolver.Resolver() resolvers.nameservers = ['8.8.8.8', '114.114.114.114', '223.5.5.5'] c = 0 def check_subdomain(subdomain): global c try: resolvers.resolve(subdomain, 'A') return subdomain, True except Exception: c += 1 return subdomain, False if __name__ == "__main__": target_url = "google.com" subdomains = [] with open('subdomain1k.txt', 'r') as f: for line in f: word = line.strip() if word: subdomains.append(f"{word}.{target_url}") with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [executor.submit(check_subdomain, s) for s in subdomains] for future in as_completed(futures): domain, is_exist = future.result() if is_exist: print(domain)
内容的提问来源于stack exchange,提问作者johannes791
相关产品推荐
相关产品推荐

