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

Python多线程爬虫不是靠开一堆线程硬怼,而是用 threading 控制并发节奏,避免被封、减少等待、提升整体抓取效率。关键在合理复用线程、加锁保护共享资源、控制请求频率。
用 Queue + threading.Thread 做任务分发
手动管理线程数量比直接 start() 一堆线程更稳妥。推荐搭配 queue.Queue 实现生产者-消费者模型:
- 主线程把待爬 URL 放进队列(生产者)
- 多个工作线程从队列取 URL 并请求(消费者),处理完自动取下一个
- 队列自带线程安全,不用额外加锁
示例片段:
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:
标签: python js json app session csv ai 爬虫
还木有评论哦,快来抢沙发吧~