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.

Files changed (68) hide show
  1. crawlo/__init__.py +2 -1
  2. crawlo/__version__.py +1 -1
  3. crawlo/commands/genspider.py +68 -42
  4. crawlo/commands/list.py +102 -93
  5. crawlo/commands/startproject.py +89 -4
  6. crawlo/commands/utils.py +187 -0
  7. crawlo/config.py +280 -0
  8. crawlo/core/engine.py +16 -3
  9. crawlo/core/enhanced_engine.py +190 -0
  10. crawlo/core/scheduler.py +113 -8
  11. crawlo/crawler.py +840 -307
  12. crawlo/downloader/__init__.py +181 -17
  13. crawlo/downloader/aiohttp_downloader.py +15 -2
  14. crawlo/downloader/cffi_downloader.py +11 -1
  15. crawlo/downloader/httpx_downloader.py +14 -3
  16. crawlo/filters/__init__.py +122 -5
  17. crawlo/filters/aioredis_filter.py +128 -36
  18. crawlo/filters/memory_filter.py +99 -32
  19. crawlo/middleware/proxy.py +11 -8
  20. crawlo/middleware/retry.py +40 -5
  21. crawlo/mode_manager.py +201 -0
  22. crawlo/network/__init__.py +17 -3
  23. crawlo/network/request.py +118 -10
  24. crawlo/network/response.py +131 -28
  25. crawlo/pipelines/__init__.py +1 -1
  26. crawlo/pipelines/csv_pipeline.py +317 -0
  27. crawlo/pipelines/json_pipeline.py +219 -0
  28. crawlo/queue/__init__.py +0 -0
  29. crawlo/queue/pqueue.py +37 -0
  30. crawlo/queue/queue_manager.py +304 -0
  31. crawlo/queue/redis_priority_queue.py +192 -0
  32. crawlo/settings/default_settings.py +68 -9
  33. crawlo/spider/__init__.py +576 -66
  34. crawlo/task_manager.py +4 -1
  35. crawlo/templates/project/middlewares.py.tmpl +56 -45
  36. crawlo/templates/project/pipelines.py.tmpl +308 -36
  37. crawlo/templates/project/run.py.tmpl +239 -0
  38. crawlo/templates/project/settings.py.tmpl +211 -17
  39. crawlo/templates/spider/spider.py.tmpl +153 -7
  40. crawlo/utils/controlled_spider_mixin.py +336 -0
  41. crawlo/utils/large_scale_config.py +287 -0
  42. crawlo/utils/large_scale_helper.py +344 -0
  43. crawlo/utils/queue_helper.py +176 -0
  44. crawlo/utils/request_serializer.py +220 -0
  45. crawlo-1.1.2.dist-info/METADATA +567 -0
  46. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
  47. tests/test_final_validation.py +154 -0
  48. tests/test_redis_config.py +29 -0
  49. tests/test_redis_queue.py +225 -0
  50. tests/test_request_serialization.py +71 -0
  51. tests/test_scheduler.py +242 -0
  52. crawlo/pipelines/mysql_batch_pipline.py +0 -273
  53. crawlo/utils/pqueue.py +0 -174
  54. crawlo-1.1.1.dist-info/METADATA +0 -220
  55. examples/baidu_spider/__init__.py +0 -7
  56. examples/baidu_spider/demo.py +0 -94
  57. examples/baidu_spider/items.py +0 -46
  58. examples/baidu_spider/middleware.py +0 -49
  59. examples/baidu_spider/pipeline.py +0 -55
  60. examples/baidu_spider/run.py +0 -27
  61. examples/baidu_spider/settings.py +0 -121
  62. examples/baidu_spider/spiders/__init__.py +0 -7
  63. examples/baidu_spider/spiders/bai_du.py +0 -61
  64. examples/baidu_spider/spiders/miit.py +0 -159
  65. examples/baidu_spider/spiders/sina.py +0 -79
  66. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
  67. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
  68. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,336 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 受控爬虫混入类
5
+ 解决 start_requests() yield 上万个请求时的并发控制问题
6
+ """
7
+ import asyncio
8
+ import time
9
+ from typing import Generator, Optional, Set
10
+ from collections import deque
11
+
12
+ from crawlo import Request
13
+ from crawlo.utils.log import get_logger
14
+
15
+
16
+ class ControlledRequestMixin:
17
+ """
18
+ 受控请求生成混入类
19
+
20
+ 解决问题:
21
+ 1. start_requests() 同时yield上万个请求导致内存爆炸
22
+ 2. 不遵守CONCURRENCY设置,无限制创建请求
23
+ 3. 队列积压过多请求影响性能
24
+
25
+ 解决方案:
26
+ 1. 按需生成请求,根据实际并发能力控制
27
+ 2. 动态监控队列状态,智能调节生成速度
28
+ 3. 支持背压控制,避免队列积压
29
+ """
30
+
31
+ def __init__(self):
32
+ self.logger = get_logger(self.__class__.__name__)
33
+
34
+ # 受控生成配置
35
+ self.max_pending_requests = 100 # 最大待处理请求数
36
+ self.batch_size = 50 # 每批生成请求数
37
+ self.generation_interval = 0.1 # 生成间隔(秒)
38
+ self.backpressure_threshold = 200 # 背压阈值
39
+
40
+ # 内部状态
41
+ self._original_start_requests = None
42
+ self._pending_count = 0
43
+ self._total_generated = 0
44
+ self._generation_paused = False
45
+
46
+ # 性能监控
47
+ self._last_generation_time = 0
48
+ self._generation_stats = {
49
+ 'generated': 0,
50
+ 'skipped': 0,
51
+ 'backpressure_events': 0
52
+ }
53
+
54
+ def start_requests(self) -> Generator[Request, None, None]:
55
+ """
56
+ 受控的 start_requests 实现
57
+
58
+ 注意:这个方法会替换原始的 start_requests,
59
+ 原始请求将通过 _original_start_requests() 提供
60
+ """
61
+ # 保存原始的请求生成器
62
+ if hasattr(self, '_original_start_requests') and self._original_start_requests:
63
+ original_generator = self._original_start_requests()
64
+ else:
65
+ # 如果子类没有定义 _original_start_requests,尝试调用原始方法
66
+ original_generator = self._get_original_requests()
67
+
68
+ # 使用受控生成器包装原始生成器
69
+ yield from self._controlled_request_generator(original_generator)
70
+
71
+ def _original_start_requests(self) -> Generator[Request, None, None]:
72
+ """
73
+ 子类应该实现这个方法,提供原始的请求生成逻辑
74
+
75
+ 示例:
76
+ def _original_start_requests(self):
77
+ for i in range(50000): # 5万个请求
78
+ yield Request(url=f"https://example.com/page/{i}")
79
+ """
80
+ raise NotImplementedError(
81
+ "子类必须实现 _original_start_requests() 方法,"
82
+ "或者确保原始的 start_requests() 方法存在"
83
+ )
84
+
85
+ def _get_original_requests(self) -> Generator[Request, None, None]:
86
+ """尝试获取原始请求(向后兼容)"""
87
+ # 这里可以尝试调用父类的 start_requests 或其他方式
88
+ # 具体实现取决于你的需求
89
+ return iter([]) # 默认返回空生成器
90
+
91
+ def _controlled_request_generator(self, original_generator) -> Generator[Request, None, None]:
92
+ """受控的请求生成器"""
93
+ self.logger.info(f"🎛️ 启动受控请求生成器 (最大待处理: {self.max_pending_requests})")
94
+
95
+ request_buffer = deque()
96
+ batch_count = 0
97
+
98
+ try:
99
+ # 分批处理原始请求
100
+ for request in original_generator:
101
+ request_buffer.append(request)
102
+
103
+ # 当缓冲区达到批次大小时,进行控制检查
104
+ if len(request_buffer) >= self.batch_size:
105
+ yield from self._yield_controlled_batch(request_buffer)
106
+ batch_count += 1
107
+
108
+ # 每批次后检查是否需要暂停
109
+ if self._should_pause_generation():
110
+ self._wait_for_capacity()
111
+
112
+ # 处理剩余的请求
113
+ if request_buffer:
114
+ yield from self._yield_controlled_batch(request_buffer)
115
+
116
+ except Exception as e:
117
+ self.logger.error(f"❌ 受控请求生成失败: {e}")
118
+ raise
119
+
120
+ self.logger.info(
121
+ f"🎉 受控请求生成完成!"
122
+ f"总计: {self._generation_stats['generated']}, "
123
+ f"跳过: {self._generation_stats['skipped']}, "
124
+ f"背压事件: {self._generation_stats['backpressure_events']}"
125
+ )
126
+
127
+ def _yield_controlled_batch(self, request_buffer: deque) -> Generator[Request, None, None]:
128
+ """分批受控 yield 请求"""
129
+ while request_buffer:
130
+ # 检查当前系统负载
131
+ if self._should_pause_generation():
132
+ self.logger.debug("⏸️ 检测到系统负载过高,暂停生成")
133
+ self._generation_stats['backpressure_events'] += 1
134
+ self._wait_for_capacity()
135
+
136
+ # yield 一个请求
137
+ request = request_buffer.popleft()
138
+
139
+ # 可以在这里添加额外的请求处理逻辑
140
+ processed_request = self._process_request_before_yield(request)
141
+ if processed_request:
142
+ self._total_generated += 1
143
+ self._generation_stats['generated'] += 1
144
+ self._last_generation_time = time.time()
145
+ yield processed_request
146
+ else:
147
+ self._generation_stats['skipped'] += 1
148
+
149
+ # 控制生成速度
150
+ if self.generation_interval > 0:
151
+ time.sleep(self.generation_interval)
152
+
153
+ def _should_pause_generation(self) -> bool:
154
+ """判断是否应该暂停请求生成"""
155
+ # 检查队列大小(如果可以访问scheduler的话)
156
+ if hasattr(self, 'crawler') and self.crawler:
157
+ engine = getattr(self.crawler, 'engine', None)
158
+ if engine and engine.scheduler:
159
+ queue_size = len(engine.scheduler)
160
+ if queue_size > self.backpressure_threshold:
161
+ return True
162
+
163
+ # 检查任务管理器负载
164
+ if hasattr(self, 'crawler') and self.crawler:
165
+ engine = getattr(self.crawler, 'engine', None)
166
+ if engine and engine.task_manager:
167
+ current_tasks = len(engine.task_manager.current_task)
168
+ concurrency = getattr(engine.task_manager, 'semaphore', None)
169
+ if concurrency and hasattr(concurrency, '_initial_value'):
170
+ max_concurrency = concurrency._initial_value
171
+ # 如果当前任务数接近最大并发数,暂停生成
172
+ if current_tasks >= max_concurrency * 0.8: # 80% 阈值
173
+ return True
174
+
175
+ return False
176
+
177
+ def _wait_for_capacity(self):
178
+ """等待系统有足够容量"""
179
+ wait_time = 0.1
180
+ max_wait = 5.0
181
+
182
+ while self._should_pause_generation() and wait_time < max_wait:
183
+ time.sleep(wait_time)
184
+ wait_time = min(wait_time * 1.2, max_wait) # 指数退避
185
+
186
+ def _process_request_before_yield(self, request: Request) -> Optional[Request]:
187
+ """
188
+ 在 yield 请求前进行处理
189
+ 子类可以重写这个方法来添加自定义逻辑
190
+
191
+ 返回 None 表示跳过这个请求
192
+ """
193
+ return request
194
+
195
+ def get_generation_stats(self) -> dict:
196
+ """获取生成统计信息"""
197
+ return {
198
+ **self._generation_stats,
199
+ 'total_generated': self._total_generated,
200
+ 'last_generation_time': self._last_generation_time
201
+ }
202
+
203
+
204
+ class AsyncControlledRequestMixin:
205
+ """
206
+ 异步版本的受控请求混入类
207
+
208
+ 使用asyncio来实现更精确的并发控制
209
+ """
210
+
211
+ def __init__(self):
212
+ self.logger = get_logger(self.__class__.__name__)
213
+
214
+ # 异步控制配置
215
+ self.max_concurrent_generations = 10 # 最大同时生成数
216
+ self.generation_semaphore = None
217
+ self.queue_monitor_interval = 1.0 # 队列监控间隔
218
+
219
+ # 异步状态
220
+ self._generation_tasks = set()
221
+ self._monitoring_task = None
222
+ self._stop_generation = False
223
+
224
+ async def start_requests_async(self) -> Generator[Request, None, None]:
225
+ """异步版本的受控请求生成"""
226
+ # 初始化信号量
227
+ self.generation_semaphore = asyncio.Semaphore(self.max_concurrent_generations)
228
+
229
+ # 启动队列监控
230
+ self._monitoring_task = asyncio.create_task(self._monitor_queue_load())
231
+
232
+ try:
233
+ # 获取原始请求
234
+ original_requests = self._original_start_requests()
235
+
236
+ # 分批异步处理
237
+ batch = []
238
+ async for request in self._async_request_wrapper(original_requests):
239
+ batch.append(request)
240
+
241
+ if len(batch) >= 50: # 批次大小
242
+ yield from await self._process_async_batch(batch)
243
+ batch = []
244
+
245
+ # 处理剩余请求
246
+ if batch:
247
+ yield from await self._process_async_batch(batch)
248
+
249
+ finally:
250
+ # 清理
251
+ self._stop_generation = True
252
+ if self._monitoring_task:
253
+ self._monitoring_task.cancel()
254
+
255
+ # 等待所有生成任务完成
256
+ if self._generation_tasks:
257
+ await asyncio.gather(*self._generation_tasks, return_exceptions=True)
258
+
259
+ async def _async_request_wrapper(self, sync_generator):
260
+ """将同步生成器包装为异步"""
261
+ for request in sync_generator:
262
+ yield request
263
+ await asyncio.sleep(0) # 让出控制权
264
+
265
+ async def _process_async_batch(self, batch):
266
+ """异步处理批次请求"""
267
+ async def process_single_request(request):
268
+ async with self.generation_semaphore:
269
+ # 等待合适的时机
270
+ while self._should_pause_generation() and not self._stop_generation:
271
+ await asyncio.sleep(0.1)
272
+
273
+ if not self._stop_generation:
274
+ return self._process_request_before_yield(request)
275
+ return None
276
+
277
+ # 并发处理批次中的请求
278
+ tasks = [process_single_request(req) for req in batch]
279
+ results = await asyncio.gather(*tasks, return_exceptions=True)
280
+
281
+ # yield 处理完的请求
282
+ for result in results:
283
+ if result and not isinstance(result, Exception):
284
+ yield result
285
+
286
+ async def _monitor_queue_load(self):
287
+ """监控队列负载"""
288
+ while not self._stop_generation:
289
+ try:
290
+ # 这里可以添加队列负载监控逻辑
291
+ await asyncio.sleep(self.queue_monitor_interval)
292
+ except asyncio.CancelledError:
293
+ break
294
+ except Exception as e:
295
+ self.logger.warning(f"队列监控异常: {e}")
296
+ await asyncio.sleep(1.0)
297
+
298
+
299
+ # 使用示例和文档
300
+ USAGE_EXAMPLE = '''
301
+ # 使用示例:
302
+
303
+ class MyControlledSpider(Spider, ControlledRequestMixin):
304
+ name = 'controlled_spider'
305
+
306
+ def __init__(self):
307
+ Spider.__init__(self)
308
+ ControlledRequestMixin.__init__(self)
309
+
310
+ # 配置受控生成参数
311
+ self.max_pending_requests = 200
312
+ self.batch_size = 100
313
+ self.generation_interval = 0.05
314
+
315
+ def _original_start_requests(self):
316
+ """提供原始的大量请求"""
317
+ for i in range(50000): # 5万个请求
318
+ yield Request(url=f"https://example.com/page/{i}")
319
+
320
+ def _process_request_before_yield(self, request):
321
+ """可选:在yield前处理请求"""
322
+ # 可以添加去重、优先级设置等逻辑
323
+ return request
324
+
325
+ async def parse(self, response):
326
+ # 解析逻辑
327
+ yield {"url": response.url}
328
+
329
+ # 使用时:
330
+ from crawlo.crawler import CrawlerProcess
331
+
332
+ process = CrawlerProcess()
333
+ process.settings.set('CONCURRENCY', 16) # 设置并发数
334
+ process.crawl(MyControlledSpider)
335
+ process.start()
336
+ '''
@@ -0,0 +1,287 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 大规模爬虫配置助手
5
+ 提供针对上万请求场景的优化配置
6
+ """
7
+ from typing import Dict, Any
8
+
9
+ from crawlo.utils.queue_helper import QueueHelper
10
+
11
+
12
+ class LargeScaleConfig:
13
+ """大规模爬虫配置类"""
14
+
15
+ @staticmethod
16
+ def conservative_config(concurrency: int = 8) -> Dict[str, Any]:
17
+ """
18
+ 保守配置 - 适用于资源有限的环境
19
+
20
+ 特点:
21
+ - 较小的队列容量
22
+ - 较低的并发数
23
+ - 较长的延迟
24
+ """
25
+ config = QueueHelper.use_redis_queue(
26
+ queue_name="crawlo:conservative",
27
+ max_retries=3,
28
+ timeout=300
29
+ )
30
+
31
+ config.update({
32
+ # 并发控制
33
+ 'CONCURRENCY': concurrency,
34
+ 'SCHEDULER_MAX_QUEUE_SIZE': concurrency * 10, # 队列容量为并发数的10倍
35
+ 'MAX_RUNNING_SPIDERS': 1,
36
+
37
+ # 请求控制
38
+ 'DOWNLOAD_DELAY': 0.2,
39
+ 'RANDOMNESS': True,
40
+ 'RANDOM_RANGE': (0.8, 1.5),
41
+
42
+ # 内存控制
43
+ 'DOWNLOAD_MAXSIZE': 5 * 1024 * 1024, # 5MB
44
+ 'CONNECTION_POOL_LIMIT': concurrency * 2,
45
+
46
+ # 重试策略
47
+ 'MAX_RETRY_TIMES': 2,
48
+
49
+ # 使用增强引擎
50
+ 'ENGINE_CLASS': 'crawlo.core.enhanced_engine.EnhancedEngine'
51
+ })
52
+
53
+ return config
54
+
55
+ @staticmethod
56
+ def balanced_config(concurrency: int = 16) -> Dict[str, Any]:
57
+ """
58
+ 平衡配置 - 适用于一般生产环境
59
+
60
+ 特点:
61
+ - 中等的队列容量
62
+ - 平衡的并发数
63
+ - 适中的延迟
64
+ """
65
+ config = QueueHelper.use_redis_queue(
66
+ queue_name="crawlo:balanced",
67
+ max_retries=5,
68
+ timeout=600
69
+ )
70
+
71
+ config.update({
72
+ # 并发控制
73
+ 'CONCURRENCY': concurrency,
74
+ 'SCHEDULER_MAX_QUEUE_SIZE': concurrency * 15,
75
+ 'MAX_RUNNING_SPIDERS': 2,
76
+
77
+ # 请求控制
78
+ 'DOWNLOAD_DELAY': 0.1,
79
+ 'RANDOMNESS': True,
80
+ 'RANDOM_RANGE': (0.5, 1.2),
81
+
82
+ # 内存控制
83
+ 'DOWNLOAD_MAXSIZE': 10 * 1024 * 1024, # 10MB
84
+ 'CONNECTION_POOL_LIMIT': concurrency * 3,
85
+
86
+ # 重试策略
87
+ 'MAX_RETRY_TIMES': 3,
88
+
89
+ # 使用增强引擎
90
+ 'ENGINE_CLASS': 'crawlo.core.enhanced_engine.EnhancedEngine'
91
+ })
92
+
93
+ return config
94
+
95
+ @staticmethod
96
+ def aggressive_config(concurrency: int = 32) -> Dict[str, Any]:
97
+ """
98
+ 激进配置 - 适用于高性能环境
99
+
100
+ 特点:
101
+ - 大的队列容量
102
+ - 高并发数
103
+ - 较短的延迟
104
+ """
105
+ config = QueueHelper.use_redis_queue(
106
+ queue_name="crawlo:aggressive",
107
+ max_retries=10,
108
+ timeout=900
109
+ )
110
+
111
+ config.update({
112
+ # 并发控制
113
+ 'CONCURRENCY': concurrency,
114
+ 'SCHEDULER_MAX_QUEUE_SIZE': concurrency * 20,
115
+ 'MAX_RUNNING_SPIDERS': 3,
116
+
117
+ # 请求控制
118
+ 'DOWNLOAD_DELAY': 0.05,
119
+ 'RANDOMNESS': True,
120
+ 'RANDOM_RANGE': (0.3, 1.0),
121
+
122
+ # 内存控制
123
+ 'DOWNLOAD_MAXSIZE': 20 * 1024 * 1024, # 20MB
124
+ 'CONNECTION_POOL_LIMIT': concurrency * 4,
125
+
126
+ # 重试策略
127
+ 'MAX_RETRY_TIMES': 5,
128
+
129
+ # 使用增强引擎
130
+ 'ENGINE_CLASS': 'crawlo.core.enhanced_engine.EnhancedEngine'
131
+ })
132
+
133
+ return config
134
+
135
+ @staticmethod
136
+ def memory_optimized_config(concurrency: int = 12) -> Dict[str, Any]:
137
+ """
138
+ 内存优化配置 - 适用于大规模但内存受限的场景
139
+
140
+ 特点:
141
+ - 小队列,快速流转
142
+ - 严格的内存控制
143
+ - 使用Redis减少内存压力
144
+ """
145
+ config = QueueHelper.use_redis_queue(
146
+ queue_name="crawlo:memory_optimized",
147
+ max_retries=3,
148
+ timeout=300
149
+ )
150
+
151
+ config.update({
152
+ # 并发控制
153
+ 'CONCURRENCY': concurrency,
154
+ 'SCHEDULER_MAX_QUEUE_SIZE': concurrency * 5, # 小队列
155
+ 'MAX_RUNNING_SPIDERS': 1,
156
+
157
+ # 请求控制
158
+ 'DOWNLOAD_DELAY': 0.1,
159
+ 'RANDOMNESS': False, # 减少随机性降低内存使用
160
+
161
+ # 严格的内存控制
162
+ 'DOWNLOAD_MAXSIZE': 2 * 1024 * 1024, # 2MB
163
+ 'DOWNLOAD_WARN_SIZE': 512 * 1024, # 512KB
164
+ 'CONNECTION_POOL_LIMIT': concurrency,
165
+
166
+ # 重试策略
167
+ 'MAX_RETRY_TIMES': 2,
168
+
169
+ # 使用增强引擎
170
+ 'ENGINE_CLASS': 'crawlo.core.enhanced_engine.EnhancedEngine'
171
+ })
172
+
173
+ return config
174
+
175
+
176
+ def apply_large_scale_config(settings_dict: Dict[str, Any], config_type: str = "balanced", concurrency: int = None):
177
+ """
178
+ 应用大规模配置
179
+
180
+ Args:
181
+ settings_dict: 设置字典
182
+ config_type: 配置类型 ("conservative", "balanced", "aggressive", "memory_optimized")
183
+ concurrency: 并发数(可选,不指定则使用默认值)
184
+ """
185
+ config_map = {
186
+ "conservative": LargeScaleConfig.conservative_config,
187
+ "balanced": LargeScaleConfig.balanced_config,
188
+ "aggressive": LargeScaleConfig.aggressive_config,
189
+ "memory_optimized": LargeScaleConfig.memory_optimized_config
190
+ }
191
+
192
+ if config_type not in config_map:
193
+ raise ValueError(f"不支持的配置类型: {config_type}")
194
+
195
+ if concurrency:
196
+ config = config_map[config_type](concurrency)
197
+ else:
198
+ config = config_map[config_type]()
199
+
200
+ settings_dict.update(config)
201
+
202
+ return config
203
+
204
+
205
+ # 使用示例和说明
206
+ USAGE_GUIDE = """
207
+ # 大规模爬虫配置使用指南
208
+
209
+ ## 1. 选择合适的配置类型
210
+
211
+ ### Conservative (保守型)
212
+ - 适用场景:资源受限、网络不稳定的环境
213
+ - 并发数:8 (默认)
214
+ - 队列容量:80
215
+ - 延迟:200ms
216
+ - 使用场景:个人开发、小规模爬取
217
+
218
+ ### Balanced (平衡型)
219
+ - 适用场景:一般生产环境
220
+ - 并发数:16 (默认)
221
+ - 队列容量:240
222
+ - 延迟:100ms
223
+ - 使用场景:中小企业生产环境
224
+
225
+ ### Aggressive (激进型)
226
+ - 适用场景:高性能服务器、对速度要求高
227
+ - 并发数:32 (默认)
228
+ - 队列容量:640
229
+ - 延迟:50ms
230
+ - 使用场景:大公司、高并发需求
231
+
232
+ ### Memory Optimized (内存优化型)
233
+ - 适用场景:大规模爬取但内存受限
234
+ - 并发数:12 (默认)
235
+ - 队列容量:60 (小队列快速流转)
236
+ - 延迟:100ms
237
+ - 使用场景:处理数万/数十万请求但内存有限
238
+
239
+ ## 2. 使用方法
240
+
241
+ ```python
242
+ # 方法1:在 settings.py 中直接配置
243
+ from crawlo.utils.large_scale_config import apply_large_scale_config
244
+
245
+ # 使用平衡配置,16并发
246
+ apply_large_scale_config(locals(), "balanced", 16)
247
+
248
+ # 方法2:在爬虫代码中动态配置
249
+ from crawlo.crawler import CrawlerProcess
250
+ from crawlo.utils.large_scale_config import LargeScaleConfig
251
+
252
+ process = CrawlerProcess()
253
+ config = LargeScaleConfig.memory_optimized_config(20) # 20并发的内存优化配置
254
+ process.settings.update(config)
255
+
256
+ # 方法3:自定义配置
257
+ config = LargeScaleConfig.balanced_config(24) # 24并发
258
+ config['DOWNLOAD_DELAY'] = 0.05 # 自定义延迟
259
+ process.settings.update(config)
260
+ ```
261
+
262
+ ## 3. 针对不同场景的建议
263
+
264
+ ### 处理5万+请求
265
+ ```python
266
+ # 推荐内存优化配置
267
+ apply_large_scale_config(locals(), "memory_optimized", 20)
268
+ ```
269
+
270
+ ### 高速爬取但服务器性能好
271
+ ```python
272
+ # 推荐激进配置
273
+ apply_large_scale_config(locals(), "aggressive", 40)
274
+ ```
275
+
276
+ ### 资源受限但要稳定运行
277
+ ```python
278
+ # 推荐保守配置
279
+ apply_large_scale_config(locals(), "conservative", 6)
280
+ ```
281
+
282
+ ### 平衡性能和稳定性
283
+ ```python
284
+ # 推荐平衡配置
285
+ apply_large_scale_config(locals(), "balanced", 18)
286
+ ```
287
+ """