Python多线程爬虫应采用Queue+threading.Thread的生产者-消费者模型,合理控制并发数、加锁保护共享资源、添加延时与异常处理,避免被封;I/O密集型任务适用,CPU密集型则选multiprocessing。

Python多线程爬虫不是靠开一堆线程硬怼,而是用 threading 控制并发节奏,避免被封、减少等待、提升整体抓取效率。关键在合理复用线程、加锁保护共享资源、控制请求频率。
手动管理线程数量比直接 start() 一堆线程更稳妥。推荐搭配 queue.Queue 实现生产者-消费者模型:
示例片段:
import threading
import queue
import requests
<p>url_queue = queue.Queue()
results = []</p><p>def worker():
while True:
url = url_queue.get()
if url is None: # 退出信号
break
try:
resp = requests.get(url, timeout=5)
results.append((url, resp.status_code))
except Exception as e:
results.append((url, f"error: {e}"))
url_queue.task_done() # 标记完成</p><h1>启动 4 个线程</h1><p>threads = []
for _ in range(4):
t = threading.Thread(target=worker)
t.start()
threads.append(t)</p><h1>添加任务</h1><p>for u in ["<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>", "<a href="https://www.php.cn/link/ef246753a70fce661e16668898810624">https://www.php.cn/link/ef246753a70fce661e16668898810624</a>"]:
url_queue.put(u)</p><p>url_queue.join() # 等所有任务完成</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><h1>发送退出信号</h1><p>for _ in threads:
url_queue.put(None)
for t in threads:
t.join()
像写文件、更新全局列表、计数器这类操作,多个线程同时执行会出错(比如少记一次、覆盖数据)。必须用 threading.Lock:
lock = threading.Lock()
lock.acquire(),写完立刻 lock.release()
with lock: 语句,自动释放例如保存结果到 CSV 文件时:
import csv
lock = threading.Lock()
<p>def save_to_csv(url, status):
with lock: # 确保同一时间只有一个线程在写
with open("log.csv", "a", newline="") as f:
writer = csv.writer(f)
writer.writerow([url, status])
多线程不等于“越快越好”。高频请求会触发目标网站的频率限制或验证码:
time.sleep(0.5)(根据目标调整)requests.exceptions.RequestException,避免单个失败导致线程退出timeout,防止某个 URL 卡死整个线程纯 CPU 密集型任务(如解析大量 JSON、计算哈希)用 threading 效果差,因为 CPython 有 GIL;此时应选 multiprocessing。而爬虫本质是 I/O 密集型,threading 正合适——等响应时线程挂起,CPU 可切去干别的。
如果需要更高并发或更优雅的协程支持,可后续升级到 asyncio + aiohttp,但 threading 入门快、逻辑直白,适合中小规模稳定采集。
以上就是Python多线程爬虫怎么写_threading实战说明【教程】的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号