crawlo 1.1.1__py3-none-any.whl → 1.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of crawlo might be problematic. Click here for more details.
- crawlo/__init__.py +2 -1
- crawlo/__version__.py +1 -1
- crawlo/commands/genspider.py +68 -42
- crawlo/commands/list.py +102 -93
- crawlo/commands/startproject.py +89 -4
- crawlo/commands/utils.py +187 -0
- crawlo/config.py +280 -0
- crawlo/core/engine.py +16 -3
- crawlo/core/enhanced_engine.py +190 -0
- crawlo/core/scheduler.py +113 -8
- crawlo/crawler.py +840 -307
- crawlo/downloader/__init__.py +181 -17
- crawlo/downloader/aiohttp_downloader.py +15 -2
- crawlo/downloader/cffi_downloader.py +11 -1
- crawlo/downloader/httpx_downloader.py +14 -3
- crawlo/filters/__init__.py +122 -5
- crawlo/filters/aioredis_filter.py +128 -36
- crawlo/filters/memory_filter.py +99 -32
- crawlo/middleware/proxy.py +11 -8
- crawlo/middleware/retry.py +40 -5
- crawlo/mode_manager.py +201 -0
- crawlo/network/__init__.py +17 -3
- crawlo/network/request.py +118 -10
- crawlo/network/response.py +131 -28
- crawlo/pipelines/__init__.py +1 -1
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/queue/__init__.py +0 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +304 -0
- crawlo/queue/redis_priority_queue.py +192 -0
- crawlo/settings/default_settings.py +68 -9
- crawlo/spider/__init__.py +576 -66
- crawlo/task_manager.py +4 -1
- crawlo/templates/project/middlewares.py.tmpl +56 -45
- crawlo/templates/project/pipelines.py.tmpl +308 -36
- crawlo/templates/project/run.py.tmpl +239 -0
- crawlo/templates/project/settings.py.tmpl +211 -17
- crawlo/templates/spider/spider.py.tmpl +153 -7
- crawlo/utils/controlled_spider_mixin.py +336 -0
- crawlo/utils/large_scale_config.py +287 -0
- crawlo/utils/large_scale_helper.py +344 -0
- crawlo/utils/queue_helper.py +176 -0
- crawlo/utils/request_serializer.py +220 -0
- crawlo-1.1.2.dist-info/METADATA +567 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
- tests/test_final_validation.py +154 -0
- tests/test_redis_config.py +29 -0
- tests/test_redis_queue.py +225 -0
- tests/test_request_serialization.py +71 -0
- tests/test_scheduler.py +242 -0
- crawlo/pipelines/mysql_batch_pipline.py +0 -273
- crawlo/utils/pqueue.py +0 -174
- crawlo-1.1.1.dist-info/METADATA +0 -220
- examples/baidu_spider/__init__.py +0 -7
- examples/baidu_spider/demo.py +0 -94
- examples/baidu_spider/items.py +0 -46
- examples/baidu_spider/middleware.py +0 -49
- examples/baidu_spider/pipeline.py +0 -55
- examples/baidu_spider/run.py +0 -27
- examples/baidu_spider/settings.py +0 -121
- examples/baidu_spider/spiders/__init__.py +0 -7
- examples/baidu_spider/spiders/bai_du.py +0 -61
- examples/baidu_spider/spiders/miit.py +0 -159
- examples/baidu_spider/spiders/sina.py +0 -79
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
统一的队列管理器
|
|
5
|
+
提供简洁、一致的队列接口,自动处理不同队列类型的差异
|
|
6
|
+
"""
|
|
7
|
+
from typing import Optional, Dict, Any, Union
|
|
8
|
+
from enum import Enum
|
|
9
|
+
import asyncio
|
|
10
|
+
|
|
11
|
+
from crawlo.utils.log import get_logger
|
|
12
|
+
from crawlo.utils.request_serializer import RequestSerializer
|
|
13
|
+
from crawlo.queue.pqueue import SpiderPriorityQueue
|
|
14
|
+
from crawlo import Request
|
|
15
|
+
|
|
16
|
+
try:
|
|
17
|
+
from crawlo.queue.redis_priority_queue import RedisPriorityQueue
|
|
18
|
+
REDIS_AVAILABLE = True
|
|
19
|
+
except ImportError:
|
|
20
|
+
RedisPriorityQueue = None
|
|
21
|
+
REDIS_AVAILABLE = False
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class QueueType(Enum):
|
|
25
|
+
"""队列类型枚举"""
|
|
26
|
+
MEMORY = "memory"
|
|
27
|
+
REDIS = "redis"
|
|
28
|
+
AUTO = "auto" # 自动选择
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class QueueConfig:
|
|
32
|
+
"""队列配置类"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
queue_type: Union[QueueType, str] = QueueType.AUTO,
|
|
37
|
+
redis_url: Optional[str] = None,
|
|
38
|
+
redis_host: str = "127.0.0.1",
|
|
39
|
+
redis_port: int = 6379,
|
|
40
|
+
redis_password: Optional[str] = None,
|
|
41
|
+
redis_db: int = 0,
|
|
42
|
+
queue_name: str = "crawlo:requests",
|
|
43
|
+
max_queue_size: int = 1000,
|
|
44
|
+
max_retries: int = 3,
|
|
45
|
+
timeout: int = 300,
|
|
46
|
+
**kwargs
|
|
47
|
+
):
|
|
48
|
+
self.queue_type = QueueType(queue_type) if isinstance(queue_type, str) else queue_type
|
|
49
|
+
|
|
50
|
+
# Redis 配置
|
|
51
|
+
if redis_url:
|
|
52
|
+
self.redis_url = redis_url
|
|
53
|
+
else:
|
|
54
|
+
if redis_password:
|
|
55
|
+
self.redis_url = f"redis://:{redis_password}@{redis_host}:{redis_port}/{redis_db}"
|
|
56
|
+
else:
|
|
57
|
+
self.redis_url = f"redis://{redis_host}:{redis_port}/{redis_db}"
|
|
58
|
+
|
|
59
|
+
self.queue_name = queue_name
|
|
60
|
+
self.max_queue_size = max_queue_size
|
|
61
|
+
self.max_retries = max_retries
|
|
62
|
+
self.timeout = timeout
|
|
63
|
+
self.extra_config = kwargs
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_settings(cls, settings) -> 'QueueConfig':
|
|
67
|
+
"""从 settings 创建配置"""
|
|
68
|
+
return cls(
|
|
69
|
+
queue_type=settings.get('QUEUE_TYPE', QueueType.AUTO),
|
|
70
|
+
redis_url=settings.get('REDIS_URL'),
|
|
71
|
+
redis_host=settings.get('REDIS_HOST', '127.0.0.1'),
|
|
72
|
+
redis_port=settings.get_int('REDIS_PORT', 6379),
|
|
73
|
+
redis_password=settings.get('REDIS_PASSWORD'),
|
|
74
|
+
redis_db=settings.get_int('REDIS_DB', 0),
|
|
75
|
+
queue_name=settings.get('SCHEDULER_QUEUE_NAME', 'crawlo:requests'),
|
|
76
|
+
max_queue_size=settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 1000),
|
|
77
|
+
max_retries=settings.get_int('QUEUE_MAX_RETRIES', 3),
|
|
78
|
+
timeout=settings.get_int('QUEUE_TIMEOUT', 300)
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class QueueManager:
|
|
83
|
+
"""统一的队列管理器"""
|
|
84
|
+
|
|
85
|
+
def __init__(self, config: QueueConfig):
|
|
86
|
+
self.config = config
|
|
87
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
88
|
+
self.request_serializer = RequestSerializer()
|
|
89
|
+
self._queue = None
|
|
90
|
+
self._queue_semaphore = None
|
|
91
|
+
self._queue_type = None
|
|
92
|
+
self._health_status = "unknown"
|
|
93
|
+
|
|
94
|
+
async def initialize(self) -> bool:
|
|
95
|
+
"""初始化队列"""
|
|
96
|
+
try:
|
|
97
|
+
queue_type = await self._determine_queue_type()
|
|
98
|
+
self._queue = await self._create_queue(queue_type)
|
|
99
|
+
self._queue_type = queue_type
|
|
100
|
+
|
|
101
|
+
# 测试队列健康状态
|
|
102
|
+
await self._health_check()
|
|
103
|
+
|
|
104
|
+
self.logger.info(f"✅ 队列初始化成功: {queue_type.value}")
|
|
105
|
+
self.logger.info(f"📊 队列配置: {self._get_queue_info()}")
|
|
106
|
+
return True
|
|
107
|
+
|
|
108
|
+
except Exception as e:
|
|
109
|
+
self.logger.error(f"❌ 队列初始化失败: {e}")
|
|
110
|
+
self._health_status = "error"
|
|
111
|
+
return False
|
|
112
|
+
|
|
113
|
+
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
114
|
+
"""统一的入队接口"""
|
|
115
|
+
if not self._queue:
|
|
116
|
+
raise RuntimeError("队列未初始化")
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
# 序列化处理(仅对 Redis 队列)
|
|
120
|
+
if self._queue_type == QueueType.REDIS:
|
|
121
|
+
request = self.request_serializer.prepare_for_serialization(request)
|
|
122
|
+
|
|
123
|
+
# 背压控制(仅对内存队列)
|
|
124
|
+
if self._queue_semaphore:
|
|
125
|
+
# 对于大量请求,使用非阻塞式检查
|
|
126
|
+
if not self._queue_semaphore.locked():
|
|
127
|
+
await self._queue_semaphore.acquire()
|
|
128
|
+
else:
|
|
129
|
+
# 如果队列已满,返回 False 而不是阻塞
|
|
130
|
+
self.logger.warning("队列已满,跳过当前请求")
|
|
131
|
+
return False
|
|
132
|
+
|
|
133
|
+
# 统一的入队操作
|
|
134
|
+
if hasattr(self._queue, 'put'):
|
|
135
|
+
if self._queue_type == QueueType.REDIS:
|
|
136
|
+
success = await self._queue.put(request, priority)
|
|
137
|
+
else:
|
|
138
|
+
await self._queue.put(request)
|
|
139
|
+
success = True
|
|
140
|
+
else:
|
|
141
|
+
raise RuntimeError(f"队列类型 {self._queue_type} 不支持 put 操作")
|
|
142
|
+
|
|
143
|
+
if success:
|
|
144
|
+
self.logger.debug(f"✅ 请求入队成功: {request.url}")
|
|
145
|
+
|
|
146
|
+
return success
|
|
147
|
+
|
|
148
|
+
except Exception as e:
|
|
149
|
+
self.logger.error(f"❌ 请求入队失败: {e}")
|
|
150
|
+
if self._queue_semaphore:
|
|
151
|
+
self._queue_semaphore.release()
|
|
152
|
+
return False
|
|
153
|
+
|
|
154
|
+
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
155
|
+
"""统一的出队接口"""
|
|
156
|
+
if not self._queue:
|
|
157
|
+
raise RuntimeError("队列未初始化")
|
|
158
|
+
|
|
159
|
+
try:
|
|
160
|
+
request = await self._queue.get(timeout=timeout)
|
|
161
|
+
|
|
162
|
+
# 释放信号量(仅对内存队列)
|
|
163
|
+
if self._queue_semaphore and request:
|
|
164
|
+
self._queue_semaphore.release()
|
|
165
|
+
|
|
166
|
+
# 反序列化处理(仅对 Redis 队列)
|
|
167
|
+
if request and self._queue_type == QueueType.REDIS:
|
|
168
|
+
# 这里需要 spider 实例,暂时返回原始请求
|
|
169
|
+
# 实际的 callback 恢复在 scheduler 中处理
|
|
170
|
+
pass
|
|
171
|
+
|
|
172
|
+
return request
|
|
173
|
+
|
|
174
|
+
except Exception as e:
|
|
175
|
+
self.logger.error(f"❌ 请求出队失败: {e}")
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
async def size(self) -> int:
|
|
179
|
+
"""获取队列大小"""
|
|
180
|
+
if not self._queue:
|
|
181
|
+
return 0
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
if hasattr(self._queue, 'qsize'):
|
|
185
|
+
if asyncio.iscoroutinefunction(self._queue.qsize):
|
|
186
|
+
return await self._queue.qsize()
|
|
187
|
+
else:
|
|
188
|
+
return self._queue.qsize()
|
|
189
|
+
return 0
|
|
190
|
+
except Exception as e:
|
|
191
|
+
self.logger.warning(f"获取队列大小失败: {e}")
|
|
192
|
+
return 0
|
|
193
|
+
|
|
194
|
+
def empty(self) -> bool:
|
|
195
|
+
"""检查队列是否为空"""
|
|
196
|
+
try:
|
|
197
|
+
# 对于内存队列,可以同步检查
|
|
198
|
+
if self._queue_type == QueueType.MEMORY:
|
|
199
|
+
return self._queue.qsize() == 0
|
|
200
|
+
# 对于 Redis 队列,需要异步操作,这里返回近似值
|
|
201
|
+
return False
|
|
202
|
+
except Exception:
|
|
203
|
+
return True
|
|
204
|
+
|
|
205
|
+
async def close(self) -> None:
|
|
206
|
+
"""关闭队列"""
|
|
207
|
+
if self._queue and hasattr(self._queue, 'close'):
|
|
208
|
+
try:
|
|
209
|
+
await self._queue.close()
|
|
210
|
+
self.logger.info("✅ 队列已关闭")
|
|
211
|
+
except Exception as e:
|
|
212
|
+
self.logger.warning(f"关闭队列时发生错误: {e}")
|
|
213
|
+
|
|
214
|
+
def get_status(self) -> Dict[str, Any]:
|
|
215
|
+
"""获取队列状态信息"""
|
|
216
|
+
return {
|
|
217
|
+
"type": self._queue_type.value if self._queue_type else "unknown",
|
|
218
|
+
"health": self._health_status,
|
|
219
|
+
"config": self._get_queue_info(),
|
|
220
|
+
"initialized": self._queue is not None
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async def _determine_queue_type(self) -> QueueType:
|
|
224
|
+
"""确定队列类型"""
|
|
225
|
+
if self.config.queue_type == QueueType.AUTO:
|
|
226
|
+
# 自动选择:优先使用 Redis(如果可用)
|
|
227
|
+
if REDIS_AVAILABLE and self.config.redis_url:
|
|
228
|
+
# 测试 Redis 连接
|
|
229
|
+
try:
|
|
230
|
+
test_queue = RedisPriorityQueue(self.config.redis_url)
|
|
231
|
+
await test_queue.connect()
|
|
232
|
+
await test_queue.close()
|
|
233
|
+
self.logger.info("🔍 自动检测: Redis 可用,使用分布式队列")
|
|
234
|
+
return QueueType.REDIS
|
|
235
|
+
except Exception as e:
|
|
236
|
+
self.logger.warning(f"🔍 自动检测: Redis 不可用 ({e}),使用内存队列")
|
|
237
|
+
return QueueType.MEMORY
|
|
238
|
+
else:
|
|
239
|
+
self.logger.info("🔍 自动检测: Redis 未配置,使用内存队列")
|
|
240
|
+
return QueueType.MEMORY
|
|
241
|
+
|
|
242
|
+
elif self.config.queue_type == QueueType.REDIS:
|
|
243
|
+
if not REDIS_AVAILABLE:
|
|
244
|
+
raise RuntimeError("Redis 队列不可用:未安装 redis 依赖")
|
|
245
|
+
if not self.config.redis_url:
|
|
246
|
+
raise RuntimeError("Redis 队列不可用:未配置 REDIS_URL")
|
|
247
|
+
return QueueType.REDIS
|
|
248
|
+
|
|
249
|
+
elif self.config.queue_type == QueueType.MEMORY:
|
|
250
|
+
return QueueType.MEMORY
|
|
251
|
+
|
|
252
|
+
else:
|
|
253
|
+
raise ValueError(f"不支持的队列类型: {self.config.queue_type}")
|
|
254
|
+
|
|
255
|
+
async def _create_queue(self, queue_type: QueueType):
|
|
256
|
+
"""创建队列实例"""
|
|
257
|
+
if queue_type == QueueType.REDIS:
|
|
258
|
+
queue = RedisPriorityQueue(
|
|
259
|
+
redis_url=self.config.redis_url,
|
|
260
|
+
queue_name=self.config.queue_name,
|
|
261
|
+
max_retries=self.config.max_retries,
|
|
262
|
+
timeout=self.config.timeout
|
|
263
|
+
)
|
|
264
|
+
# 不需要立即连接,使用 lazy connect
|
|
265
|
+
return queue
|
|
266
|
+
|
|
267
|
+
elif queue_type == QueueType.MEMORY:
|
|
268
|
+
queue = SpiderPriorityQueue()
|
|
269
|
+
# 为内存队列设置背压控制
|
|
270
|
+
self._queue_semaphore = asyncio.Semaphore(self.config.max_queue_size)
|
|
271
|
+
return queue
|
|
272
|
+
|
|
273
|
+
else:
|
|
274
|
+
raise ValueError(f"不支持的队列类型: {queue_type}")
|
|
275
|
+
|
|
276
|
+
async def _health_check(self) -> None:
|
|
277
|
+
"""健康检查"""
|
|
278
|
+
try:
|
|
279
|
+
if self._queue_type == QueueType.REDIS:
|
|
280
|
+
# 测试 Redis 连接
|
|
281
|
+
await self._queue.connect()
|
|
282
|
+
self._health_status = "healthy"
|
|
283
|
+
else:
|
|
284
|
+
# 内存队列总是健康的
|
|
285
|
+
self._health_status = "healthy"
|
|
286
|
+
except Exception as e:
|
|
287
|
+
self.logger.warning(f"队列健康检查失败: {e}")
|
|
288
|
+
self._health_status = "unhealthy"
|
|
289
|
+
|
|
290
|
+
def _get_queue_info(self) -> Dict[str, Any]:
|
|
291
|
+
"""获取队列配置信息"""
|
|
292
|
+
info = {
|
|
293
|
+
"queue_name": self.config.queue_name,
|
|
294
|
+
"max_queue_size": self.config.max_queue_size
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if self._queue_type == QueueType.REDIS:
|
|
298
|
+
info.update({
|
|
299
|
+
"redis_url": self.config.redis_url,
|
|
300
|
+
"max_retries": self.config.max_retries,
|
|
301
|
+
"timeout": self.config.timeout
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
return info
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import pickle
|
|
2
|
+
import time
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Optional
|
|
5
|
+
import redis.asyncio as aioredis
|
|
6
|
+
|
|
7
|
+
from crawlo import Request
|
|
8
|
+
from crawlo.utils.log import get_logger
|
|
9
|
+
from crawlo.utils.request_serializer import RequestSerializer
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
logger = get_logger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RedisPriorityQueue:
|
|
16
|
+
"""
|
|
17
|
+
基于 Redis 的分布式异步优先级队列(生产级优化版)
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
redis_url: str = "redis://localhost:6379/0",
|
|
23
|
+
queue_name: str = "crawlo:requests",
|
|
24
|
+
processing_queue: str = "crawlo:processing",
|
|
25
|
+
failed_queue: str = "crawlo:failed",
|
|
26
|
+
max_retries: int = 3,
|
|
27
|
+
timeout: int = 300, # 任务处理超时时间(秒)
|
|
28
|
+
max_connections: int = 10, # 连接池大小
|
|
29
|
+
):
|
|
30
|
+
self.redis_url = redis_url
|
|
31
|
+
self.queue_name = queue_name
|
|
32
|
+
self.processing_queue = processing_queue
|
|
33
|
+
self.failed_queue = failed_queue
|
|
34
|
+
self.max_retries = max_retries
|
|
35
|
+
self.timeout = timeout
|
|
36
|
+
self.max_connections = max_connections
|
|
37
|
+
self._redis = None
|
|
38
|
+
self._lock = asyncio.Lock() # 用于连接初始化的锁
|
|
39
|
+
self.request_serializer = RequestSerializer() # 处理序列化
|
|
40
|
+
|
|
41
|
+
async def connect(self, max_retries=3, delay=1):
|
|
42
|
+
"""异步连接 Redis,支持重试"""
|
|
43
|
+
async with self._lock:
|
|
44
|
+
if self._redis is not None:
|
|
45
|
+
return self._redis
|
|
46
|
+
|
|
47
|
+
for attempt in range(max_retries):
|
|
48
|
+
try:
|
|
49
|
+
self._redis = await aioredis.from_url(
|
|
50
|
+
self.redis_url,
|
|
51
|
+
decode_responses=False, # pickle 需要 bytes
|
|
52
|
+
max_connections=self.max_connections,
|
|
53
|
+
socket_connect_timeout=5,
|
|
54
|
+
socket_timeout=30,
|
|
55
|
+
)
|
|
56
|
+
# 测试连接
|
|
57
|
+
await self._redis.ping()
|
|
58
|
+
logger.info("✅ Redis 连接成功")
|
|
59
|
+
return self._redis
|
|
60
|
+
except Exception as e:
|
|
61
|
+
logger.warning(f"⚠️ Redis 连接失败 (尝试 {attempt + 1}/{max_retries}): {e}")
|
|
62
|
+
if attempt < max_retries - 1:
|
|
63
|
+
await asyncio.sleep(delay)
|
|
64
|
+
else:
|
|
65
|
+
raise ConnectionError(f"❌ 无法连接 Redis: {e}")
|
|
66
|
+
|
|
67
|
+
async def _ensure_connection(self):
|
|
68
|
+
"""确保连接有效"""
|
|
69
|
+
if self._redis is None:
|
|
70
|
+
await self.connect()
|
|
71
|
+
try:
|
|
72
|
+
await self._redis.ping()
|
|
73
|
+
except Exception:
|
|
74
|
+
logger.warning("🔄 Redis 连接失效,尝试重连...")
|
|
75
|
+
self._redis = None
|
|
76
|
+
await self.connect()
|
|
77
|
+
|
|
78
|
+
async def put(self, request: Request, priority: int = 0) -> bool:
|
|
79
|
+
"""放入请求到队列"""
|
|
80
|
+
await self._ensure_connection()
|
|
81
|
+
score = -priority
|
|
82
|
+
key = self._get_request_key(request)
|
|
83
|
+
try:
|
|
84
|
+
# 🔥 使用专用的序列化工具清理 Request
|
|
85
|
+
clean_request = self.request_serializer.prepare_for_serialization(request)
|
|
86
|
+
|
|
87
|
+
serialized = pickle.dumps(clean_request)
|
|
88
|
+
pipe = self._redis.pipeline()
|
|
89
|
+
pipe.zadd(self.queue_name, {key: score})
|
|
90
|
+
pipe.hset(f"{self.queue_name}:data", key, serialized)
|
|
91
|
+
result = await pipe.execute()
|
|
92
|
+
|
|
93
|
+
if result[0] > 0:
|
|
94
|
+
logger.debug(f"✅ 成功入队: {request.url}")
|
|
95
|
+
return result[0] > 0
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.error(f"❌ 放入队列失败: {e}")
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
async def get(self, timeout: float = 5.0) -> Optional[Request]:
|
|
101
|
+
"""
|
|
102
|
+
获取请求(带超时)
|
|
103
|
+
:param timeout: 最大等待时间(秒),避免无限轮询
|
|
104
|
+
"""
|
|
105
|
+
await self._ensure_connection()
|
|
106
|
+
start_time = asyncio.get_event_loop().time()
|
|
107
|
+
|
|
108
|
+
while True:
|
|
109
|
+
try:
|
|
110
|
+
# 尝试获取任务
|
|
111
|
+
result = await self._redis.zpopmin(self.queue_name, count=1)
|
|
112
|
+
if result:
|
|
113
|
+
key, score = result[0]
|
|
114
|
+
serialized = await self._redis.hget(f"{self.queue_name}:data", key)
|
|
115
|
+
if not serialized:
|
|
116
|
+
continue
|
|
117
|
+
|
|
118
|
+
# 移动到 processing
|
|
119
|
+
processing_key = f"{key}:{int(time.time())}"
|
|
120
|
+
pipe = self._redis.pipeline()
|
|
121
|
+
pipe.zadd(self.processing_queue, {processing_key: time.time() + self.timeout})
|
|
122
|
+
pipe.hset(f"{self.processing_queue}:data", processing_key, serialized)
|
|
123
|
+
pipe.hdel(f"{self.queue_name}:data", key)
|
|
124
|
+
await pipe.execute()
|
|
125
|
+
|
|
126
|
+
return pickle.loads(serialized)
|
|
127
|
+
|
|
128
|
+
# 检查是否超时
|
|
129
|
+
if asyncio.get_event_loop().time() - start_time > timeout:
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
# 短暂等待,避免空轮询
|
|
133
|
+
await asyncio.sleep(0.1)
|
|
134
|
+
|
|
135
|
+
except Exception as e:
|
|
136
|
+
logger.error(f"❌ 获取队列任务失败: {e}")
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
async def ack(self, request: Request):
|
|
140
|
+
"""确认任务完成"""
|
|
141
|
+
await self._ensure_connection()
|
|
142
|
+
key = self._get_request_key(request)
|
|
143
|
+
cursor = 0
|
|
144
|
+
while True:
|
|
145
|
+
cursor, keys = await self._redis.zscan(self.processing_queue, cursor, match=f"{key}:*")
|
|
146
|
+
if keys:
|
|
147
|
+
pipe = self._redis.pipeline()
|
|
148
|
+
for k in keys:
|
|
149
|
+
pipe.zrem(self.processing_queue, k)
|
|
150
|
+
pipe.hdel(f"{self.processing_queue}:data", k)
|
|
151
|
+
await pipe.execute()
|
|
152
|
+
if cursor == 0:
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
async def fail(self, request: Request, reason: str = ""):
|
|
156
|
+
"""标记任务失败"""
|
|
157
|
+
await self._ensure_connection()
|
|
158
|
+
key = self._get_request_key(request)
|
|
159
|
+
await self.ack(request)
|
|
160
|
+
|
|
161
|
+
retry_key = f"{self.failed_queue}:retries:{key}"
|
|
162
|
+
retries = await self._redis.incr(retry_key)
|
|
163
|
+
await self._redis.expire(retry_key, 86400)
|
|
164
|
+
|
|
165
|
+
if retries <= self.max_retries:
|
|
166
|
+
await self.put(request, priority=request.priority + 1)
|
|
167
|
+
logger.info(f"🔁 任务重试 [{retries}/{self.max_retries}]: {request.url}")
|
|
168
|
+
else:
|
|
169
|
+
failed_data = {
|
|
170
|
+
"url": request.url,
|
|
171
|
+
"reason": reason,
|
|
172
|
+
"retries": retries,
|
|
173
|
+
"failed_at": time.time(),
|
|
174
|
+
"request_pickle": pickle.dumps(request).hex(), # 可选:保存完整请求
|
|
175
|
+
}
|
|
176
|
+
await self._redis.lpush(self.failed_queue, pickle.dumps(failed_data))
|
|
177
|
+
logger.error(f"❌ 任务彻底失败 [{retries}次]: {request.url}")
|
|
178
|
+
|
|
179
|
+
def _get_request_key(self, request: Request) -> str:
|
|
180
|
+
"""生成请求唯一键"""
|
|
181
|
+
return f"url:{hash(request.url)}"
|
|
182
|
+
|
|
183
|
+
async def qsize(self) -> int:
|
|
184
|
+
"""获取队列大小"""
|
|
185
|
+
await self._ensure_connection()
|
|
186
|
+
return await self._redis.zcard(self.queue_name)
|
|
187
|
+
|
|
188
|
+
async def close(self):
|
|
189
|
+
"""关闭连接"""
|
|
190
|
+
if self._redis:
|
|
191
|
+
await self._redis.close()
|
|
192
|
+
self._redis = None
|
|
@@ -16,10 +16,17 @@ PROJECT_NAME = 'crawlo'
|
|
|
16
16
|
|
|
17
17
|
# ============================== 网络请求配置 ==============================
|
|
18
18
|
|
|
19
|
-
#
|
|
20
|
-
#
|
|
21
|
-
DOWNLOADER = "crawlo.downloader.
|
|
22
|
-
# DOWNLOADER = "crawlo.downloader.
|
|
19
|
+
# 下载器选择(支持三种方式)
|
|
20
|
+
# 方式1: 直接指定类路径
|
|
21
|
+
DOWNLOADER = "crawlo.downloader.aiohttp_downloader.AioHttpDownloader"
|
|
22
|
+
# DOWNLOADER = "crawlo.downloader.cffi_downloader.CurlCffiDownloader" # 支持浏览器指纹
|
|
23
|
+
# DOWNLOADER = "crawlo.downloader.httpx_downloader.HttpXDownloader" # 支持HTTP/2
|
|
24
|
+
|
|
25
|
+
# 方式2: 使用简化名称(推荐)
|
|
26
|
+
# DOWNLOADER_TYPE = 'aiohttp' # 可选: aiohttp, httpx, curl_cffi, cffi
|
|
27
|
+
|
|
28
|
+
# 方式3: 在Spider中动态选择
|
|
29
|
+
# 可以在Spider类中设置 custom_settings = {'DOWNLOADER_TYPE': 'httpx'}
|
|
23
30
|
|
|
24
31
|
# 请求超时与安全
|
|
25
32
|
DOWNLOAD_TIMEOUT = 30 # 下载超时时间(秒)
|
|
@@ -40,10 +47,15 @@ ALLOWED_CODES = [] # 允许的状态码(空表示不限制)
|
|
|
40
47
|
|
|
41
48
|
# 连接与响应大小限制
|
|
42
49
|
CONNECTION_POOL_LIMIT = 50 # 最大并发连接数(连接池大小)
|
|
50
|
+
CONNECTION_POOL_LIMIT_PER_HOST = 20 # 每个主机的连接池大小
|
|
43
51
|
DOWNLOAD_MAXSIZE = 10 * 1024 * 1024 # 最大响应体大小(10MB)
|
|
44
52
|
DOWNLOAD_WARN_SIZE = 1024 * 1024 # 响应体警告阈值(1MB)
|
|
45
53
|
DOWNLOAD_RETRY_TIMES = MAX_RETRY_TIMES # 下载器内部重试次数(复用全局)
|
|
46
54
|
|
|
55
|
+
# 下载统计配置
|
|
56
|
+
DOWNLOADER_STATS = True # 是否启用下载器统计功能
|
|
57
|
+
DOWNLOAD_STATS = True # 是否记录下载时间和大小统计
|
|
58
|
+
|
|
47
59
|
# ============================== 并发与调度 ==============================
|
|
48
60
|
|
|
49
61
|
CONCURRENCY = 8 # 单个爬虫的并发请求数
|
|
@@ -51,6 +63,23 @@ INTERVAL = 5 # 日志统计输出间隔(秒)
|
|
|
51
63
|
DEPTH_PRIORITY = 1 # 深度优先策略优先级
|
|
52
64
|
MAX_RUNNING_SPIDERS = 3 # 最大同时运行的爬虫数
|
|
53
65
|
|
|
66
|
+
# ============================== 队列配置 ==============================
|
|
67
|
+
|
|
68
|
+
# 🎯 运行模式选择:'standalone'(单机), 'distributed'(分布式), 'auto'(自动检测)
|
|
69
|
+
RUN_MODE = 'standalone' # 默认单机模式,简单易用
|
|
70
|
+
|
|
71
|
+
# 队列类型选择:'memory'(内存), 'redis'(分布式), 'auto'(自动选择)
|
|
72
|
+
QUEUE_TYPE = 'memory' # 默认内存队列,无需外部依赖
|
|
73
|
+
SCHEDULER_MAX_QUEUE_SIZE = 2000 # 调度器队列最大容量
|
|
74
|
+
SCHEDULER_QUEUE_NAME = 'crawlo:requests' # Redis 队列名称
|
|
75
|
+
QUEUE_MAX_RETRIES = 3 # 队列操作最大重试次数
|
|
76
|
+
QUEUE_TIMEOUT = 300 # 队列操作超时时间(秒)
|
|
77
|
+
|
|
78
|
+
# 大规模爬取优化配置
|
|
79
|
+
LARGE_SCALE_BATCH_SIZE = 1000 # 批处理大小
|
|
80
|
+
LARGE_SCALE_CHECKPOINT_INTERVAL = 5000 # 进度保存间隔
|
|
81
|
+
LARGE_SCALE_MAX_MEMORY_USAGE = 500 # 最大内存使用量(MB)
|
|
82
|
+
|
|
54
83
|
# ============================== 数据存储配置 ==============================
|
|
55
84
|
|
|
56
85
|
# --- MySQL 配置 ---
|
|
@@ -82,13 +111,17 @@ REQUEST_DIR = '.'
|
|
|
82
111
|
|
|
83
112
|
# 去重过滤器类(二选一)
|
|
84
113
|
FILTER_CLASS = 'crawlo.filters.memory_filter.MemoryFilter'
|
|
85
|
-
# FILTER_CLASS = 'crawlo.filters.
|
|
114
|
+
# FILTER_CLASS = 'crawlo.filters.aioredis_filter.AioRedisFilter' # 分布式去重
|
|
86
115
|
|
|
87
116
|
# --- Redis 过滤器配置 ---
|
|
88
117
|
REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1')
|
|
89
118
|
REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
|
|
90
|
-
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', '
|
|
91
|
-
|
|
119
|
+
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', '') # 默认无密码
|
|
120
|
+
# 🔧 根据是否有密码生成不同的 URL 格式
|
|
121
|
+
if REDIS_PASSWORD:
|
|
122
|
+
REDIS_URL = f'redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/0'
|
|
123
|
+
else:
|
|
124
|
+
REDIS_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/0'
|
|
92
125
|
REDIS_KEY = 'request_fingerprint' # Redis 中存储指纹的键名
|
|
93
126
|
REDIS_TTL = 0 # 指纹过期时间(0 表示永不过期)
|
|
94
127
|
CLEANUP_FP = 0 # 程序结束时是否清理指纹(0=不清理)
|
|
@@ -153,15 +186,41 @@ CURL_BROWSER_TYPE = "chrome" # 可选: chrome, edge, safari, firef
|
|
|
153
186
|
# 自定义浏览器版本映射(可覆盖默认行为)
|
|
154
187
|
CURL_BROWSER_VERSION_MAP = {
|
|
155
188
|
"chrome": "chrome136",
|
|
156
|
-
"edge": "edge101",
|
|
189
|
+
"edge": "edge101",
|
|
157
190
|
"safari": "safari184",
|
|
158
191
|
"firefox": "firefox135",
|
|
159
192
|
# 示例:旧版本测试
|
|
160
193
|
# "chrome_legacy": "chrome110",
|
|
161
194
|
}
|
|
162
195
|
|
|
196
|
+
# Curl-Cffi 优化配置
|
|
197
|
+
CURL_RANDOMIZE_DELAY = False # 是否启用随机延迟
|
|
198
|
+
CURL_RETRY_BACKOFF = True # 是否启用指数退避重试
|
|
199
|
+
|
|
163
200
|
# 默认请求头(可被 Spider 覆盖)
|
|
164
201
|
DEFAULT_REQUEST_HEADERS = {
|
|
165
202
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
|
166
203
|
'(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
|
167
|
-
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
# ============================== 下载器优化配置 ==============================
|
|
207
|
+
|
|
208
|
+
# 下载器健康检查
|
|
209
|
+
DOWNLOADER_HEALTH_CHECK = True # 是否启用下载器健康检查
|
|
210
|
+
HEALTH_CHECK_INTERVAL = 60 # 健康检查间隔(秒)
|
|
211
|
+
|
|
212
|
+
# 请求统计配置
|
|
213
|
+
REQUEST_STATS_ENABLED = True # 是否启用请求统计
|
|
214
|
+
STATS_RESET_ON_START = False # 启动时是否重置统计
|
|
215
|
+
|
|
216
|
+
# HttpX 下载器专用配置
|
|
217
|
+
HTTPX_HTTP2 = True # 是否启用HTTP/2支持
|
|
218
|
+
HTTPX_FOLLOW_REDIRECTS = True # 是否自动跟随重定向
|
|
219
|
+
|
|
220
|
+
# AioHttp 下载器专用配置
|
|
221
|
+
AIOHTTP_AUTO_DECOMPRESS = True # 是否自动解压响应
|
|
222
|
+
AIOHTTP_FORCE_CLOSE = False # 是否强制关闭连接
|
|
223
|
+
|
|
224
|
+
# 通用优化配置
|
|
225
|
+
CONNECTION_TTL_DNS_CACHE = 300 # DNS缓存TTL(秒)
|
|
226
|
+
CONNECTION_KEEPALIVE_TIMEOUT = 15 # Keep-Alive超时(秒)
|