crawlo 1.2.7__py3-none-any.whl → 1.2.9__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 +63 -61
- crawlo/__version__.py +1 -1
- crawlo/cli.py +75 -75
- crawlo/commands/__init__.py +14 -14
- crawlo/commands/check.py +594 -594
- crawlo/commands/genspider.py +151 -151
- crawlo/commands/help.py +138 -138
- crawlo/commands/list.py +155 -155
- crawlo/commands/run.py +323 -323
- crawlo/commands/startproject.py +436 -436
- crawlo/commands/stats.py +187 -187
- crawlo/commands/utils.py +186 -186
- crawlo/config.py +312 -312
- crawlo/config_validator.py +277 -251
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +366 -365
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +256 -251
- crawlo/crawler.py +1103 -1100
- crawlo/data/__init__.py +5 -5
- crawlo/data/user_agents.py +194 -107
- crawlo/downloader/__init__.py +273 -266
- crawlo/downloader/aiohttp_downloader.py +226 -228
- crawlo/downloader/cffi_downloader.py +245 -256
- crawlo/downloader/httpx_downloader.py +259 -259
- crawlo/downloader/hybrid_downloader.py +212 -212
- crawlo/downloader/playwright_downloader.py +402 -402
- crawlo/downloader/selenium_downloader.py +472 -472
- crawlo/event.py +11 -11
- crawlo/exceptions.py +81 -81
- crawlo/extension/__init__.py +39 -39
- crawlo/extension/health_check.py +141 -141
- crawlo/extension/log_interval.py +57 -57
- crawlo/extension/log_stats.py +81 -81
- crawlo/extension/logging_extension.py +43 -43
- crawlo/extension/memory_monitor.py +104 -104
- crawlo/extension/performance_profiler.py +133 -133
- crawlo/extension/request_recorder.py +107 -107
- crawlo/filters/__init__.py +154 -154
- crawlo/filters/aioredis_filter.py +234 -234
- crawlo/filters/memory_filter.py +269 -269
- crawlo/items/__init__.py +23 -23
- crawlo/items/base.py +21 -21
- crawlo/items/fields.py +52 -52
- crawlo/items/items.py +104 -104
- crawlo/middleware/__init__.py +21 -21
- crawlo/middleware/default_header.py +132 -132
- crawlo/middleware/download_delay.py +104 -104
- crawlo/middleware/middleware_manager.py +136 -136
- crawlo/middleware/offsite.py +114 -114
- crawlo/middleware/proxy.py +386 -368
- crawlo/middleware/request_ignore.py +86 -86
- crawlo/middleware/response_code.py +163 -163
- crawlo/middleware/response_filter.py +136 -136
- crawlo/middleware/retry.py +124 -124
- crawlo/middleware/simple_proxy.py +65 -0
- crawlo/mode_manager.py +211 -211
- crawlo/network/__init__.py +21 -21
- crawlo/network/request.py +379 -338
- crawlo/network/response.py +359 -359
- crawlo/pipelines/__init__.py +21 -21
- crawlo/pipelines/bloom_dedup_pipeline.py +157 -157
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +316 -316
- crawlo/pipelines/database_dedup_pipeline.py +223 -223
- crawlo/pipelines/json_pipeline.py +218 -218
- crawlo/pipelines/memory_dedup_pipeline.py +115 -115
- crawlo/pipelines/mongo_pipeline.py +131 -131
- crawlo/pipelines/mysql_pipeline.py +317 -317
- crawlo/pipelines/pipeline_manager.py +62 -62
- crawlo/pipelines/redis_dedup_pipeline.py +167 -167
- crawlo/project.py +290 -315
- crawlo/queue/pqueue.py +37 -37
- crawlo/queue/queue_manager.py +379 -378
- crawlo/queue/redis_priority_queue.py +306 -306
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +216 -220
- crawlo/settings/setting_manager.py +163 -122
- crawlo/spider/__init__.py +639 -639
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +129 -129
- crawlo/task_manager.py +30 -30
- crawlo/templates/crawlo.cfg.tmpl +10 -10
- crawlo/templates/project/__init__.py.tmpl +3 -3
- crawlo/templates/project/items.py.tmpl +17 -17
- crawlo/templates/project/middlewares.py.tmpl +118 -118
- crawlo/templates/project/pipelines.py.tmpl +96 -96
- crawlo/templates/project/settings.py.tmpl +261 -288
- crawlo/templates/project/settings_distributed.py.tmpl +174 -157
- crawlo/templates/project/settings_gentle.py.tmpl +95 -100
- crawlo/templates/project/settings_high_performance.py.tmpl +125 -134
- crawlo/templates/project/settings_minimal.py.tmpl +30 -0
- crawlo/templates/project/settings_simple.py.tmpl +96 -98
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/run.py.tmpl +47 -45
- crawlo/templates/spider/spider.py.tmpl +143 -143
- crawlo/tools/__init__.py +200 -182
- crawlo/tools/anti_crawler.py +268 -268
- crawlo/tools/authenticated_proxy.py +240 -240
- crawlo/{cleaners → tools}/data_formatter.py +225 -225
- crawlo/tools/data_validator.py +180 -180
- crawlo/tools/date_tools.py +290 -36
- crawlo/tools/distributed_coordinator.py +388 -387
- crawlo/{cleaners → tools}/encoding_converter.py +127 -126
- crawlo/tools/request_tools.py +83 -0
- crawlo/tools/retry_mechanism.py +224 -221
- crawlo/tools/scenario_adapter.py +262 -262
- crawlo/{cleaners → tools}/text_cleaner.py +232 -232
- crawlo/utils/__init__.py +35 -35
- crawlo/utils/batch_processor.py +259 -259
- crawlo/utils/controlled_spider_mixin.py +439 -439
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/enhanced_error_handler.py +356 -356
- crawlo/utils/env_config.py +142 -142
- crawlo/utils/error_handler.py +123 -123
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +286 -286
- crawlo/utils/large_scale_helper.py +344 -344
- crawlo/utils/log.py +187 -128
- crawlo/utils/performance_monitor.py +285 -285
- crawlo/utils/queue_helper.py +175 -175
- crawlo/utils/redis_connection_pool.py +351 -351
- crawlo/utils/redis_key_validator.py +198 -198
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +218 -218
- crawlo/utils/spider_loader.py +61 -61
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +4 -4
- crawlo/utils/url.py +39 -39
- {crawlo-1.2.7.dist-info → crawlo-1.2.9.dist-info}/METADATA +1011 -764
- crawlo-1.2.9.dist-info/RECORD +219 -0
- examples/__init__.py +7 -7
- tests/DOUBLE_CRAWLO_PREFIX_FIX_REPORT.md +81 -81
- tests/__init__.py +7 -7
- tests/advanced_tools_example.py +275 -275
- tests/authenticated_proxy_example.py +107 -237
- tests/cleaners_example.py +160 -160
- tests/config_validation_demo.py +143 -103
- tests/controlled_spider_example.py +205 -205
- tests/date_tools_example.py +180 -180
- tests/debug_pipelines.py +67 -0
- tests/dynamic_loading_example.py +523 -523
- tests/dynamic_loading_test.py +104 -104
- tests/env_config_example.py +133 -133
- tests/error_handling_example.py +171 -171
- tests/redis_key_validation_demo.py +130 -130
- tests/request_params_example.py +151 -0
- tests/response_improvements_example.py +144 -144
- tests/test_advanced_tools.py +148 -148
- tests/test_all_redis_key_configs.py +145 -145
- tests/test_authenticated_proxy.py +141 -141
- tests/test_cleaners.py +54 -54
- tests/test_comprehensive.py +146 -146
- tests/test_config_consistency.py +80 -80
- tests/test_config_merge.py +153 -0
- tests/test_config_validator.py +182 -193
- tests/test_crawlo_proxy_integration.py +109 -173
- tests/test_date_tools.py +123 -123
- tests/test_default_header_middleware.py +158 -158
- tests/test_distributed.py +65 -0
- tests/test_double_crawlo_fix.py +207 -207
- tests/test_double_crawlo_fix_simple.py +124 -124
- tests/test_download_delay_middleware.py +221 -221
- tests/test_downloader_proxy_compatibility.py +268 -268
- tests/test_dynamic_downloaders_proxy.py +124 -124
- tests/test_dynamic_proxy.py +92 -92
- tests/test_dynamic_proxy_config.py +146 -146
- tests/test_dynamic_proxy_real.py +109 -109
- tests/test_edge_cases.py +303 -303
- tests/test_enhanced_error_handler.py +270 -270
- tests/test_env_config.py +121 -121
- tests/test_error_handler_compatibility.py +112 -112
- tests/test_final_validation.py +153 -153
- tests/test_framework_env_usage.py +103 -103
- tests/test_integration.py +169 -357
- tests/test_item_dedup_redis_key.py +122 -122
- tests/test_mode_consistency.py +51 -51
- tests/test_offsite_middleware.py +221 -221
- tests/test_parsel.py +29 -29
- tests/test_performance.py +327 -327
- tests/test_proxy_api.py +264 -264
- tests/test_proxy_health_check.py +32 -32
- tests/test_proxy_middleware.py +121 -121
- tests/test_proxy_middleware_enhanced.py +216 -216
- tests/test_proxy_middleware_integration.py +136 -136
- tests/test_proxy_middleware_refactored.py +185 -0
- tests/test_proxy_providers.py +56 -56
- tests/test_proxy_stats.py +19 -19
- tests/test_proxy_strategies.py +59 -59
- tests/test_queue_manager_double_crawlo.py +173 -173
- tests/test_queue_manager_redis_key.py +176 -176
- tests/test_random_user_agent.py +73 -0
- tests/test_real_scenario_proxy.py +195 -195
- tests/test_redis_config.py +28 -28
- tests/test_redis_connection_pool.py +294 -294
- tests/test_redis_key_naming.py +181 -181
- tests/test_redis_key_validator.py +123 -123
- tests/test_redis_queue.py +224 -224
- tests/test_request_ignore_middleware.py +182 -182
- tests/test_request_params.py +112 -0
- tests/test_request_serialization.py +70 -70
- tests/test_response_code_middleware.py +349 -349
- tests/test_response_filter_middleware.py +427 -427
- tests/test_response_improvements.py +152 -152
- tests/test_retry_middleware.py +241 -241
- tests/test_scheduler.py +252 -252
- tests/test_scheduler_config_update.py +133 -133
- tests/test_simple_response.py +61 -61
- tests/test_telecom_spider_redis_key.py +205 -205
- tests/test_template_content.py +87 -87
- tests/test_template_redis_key.py +134 -134
- tests/test_tools.py +159 -153
- tests/test_user_agents.py +97 -0
- tests/tools_example.py +260 -257
- tests/verify_distributed.py +117 -0
- crawlo/cleaners/__init__.py +0 -61
- crawlo/utils/date_tools.py +0 -290
- crawlo-1.2.7.dist-info/RECORD +0 -209
- {crawlo-1.2.7.dist-info → crawlo-1.2.9.dist-info}/WHEEL +0 -0
- {crawlo-1.2.7.dist-info → crawlo-1.2.9.dist-info}/entry_points.txt +0 -0
- {crawlo-1.2.7.dist-info → crawlo-1.2.9.dist-info}/top_level.txt +0 -0
crawlo/crawler.py
CHANGED
|
@@ -1,1100 +1,1103 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding: UTF-8 -*-
|
|
3
|
-
"""
|
|
4
|
-
Crawlo Crawler Module
|
|
5
|
-
====================
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
- Crawler:
|
|
10
|
-
- CrawlerProcess:
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
#
|
|
22
|
-
crawler = Crawler(MySpider, settings)
|
|
23
|
-
await crawler.crawl()
|
|
24
|
-
|
|
25
|
-
#
|
|
26
|
-
process = CrawlerProcess()
|
|
27
|
-
await process.crawl([Spider1, Spider2])
|
|
28
|
-
"""
|
|
29
|
-
from __future__ import annotations
|
|
30
|
-
import asyncio
|
|
31
|
-
import signal
|
|
32
|
-
import time
|
|
33
|
-
import threading
|
|
34
|
-
from typing import Type, Optional, Set, List, Union, Dict, Any
|
|
35
|
-
from .spider import Spider, get_global_spider_registry
|
|
36
|
-
from .core.engine import Engine
|
|
37
|
-
from .utils.log import get_logger
|
|
38
|
-
from .subscriber import Subscriber
|
|
39
|
-
from .extension import ExtensionManager
|
|
40
|
-
from .stats_collector import StatsCollector
|
|
41
|
-
from .event import spider_opened, spider_closed
|
|
42
|
-
from .settings.setting_manager import SettingManager
|
|
43
|
-
from crawlo.project import merge_settings, get_settings
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
logger =
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
"""
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def
|
|
73
|
-
with self._lock:
|
|
74
|
-
self.
|
|
75
|
-
|
|
76
|
-
def
|
|
77
|
-
with self._lock:
|
|
78
|
-
self.
|
|
79
|
-
|
|
80
|
-
def
|
|
81
|
-
with self._lock:
|
|
82
|
-
self.
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def
|
|
89
|
-
with self._lock:
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
'
|
|
93
|
-
'
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
self.
|
|
127
|
-
self.
|
|
128
|
-
self.
|
|
129
|
-
self.
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
"""
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
#
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
self.
|
|
170
|
-
|
|
171
|
-
#
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
self.
|
|
181
|
-
|
|
182
|
-
#
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
self.
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
self.
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
if not self.spider
|
|
224
|
-
raise
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def
|
|
253
|
-
"""
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
""
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
""
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
"""
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
#
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
)
|
|
454
|
-
self.
|
|
455
|
-
|
|
456
|
-
#
|
|
457
|
-
self.
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
self.
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
"""
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
"""
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
#
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
#
|
|
835
|
-
await
|
|
836
|
-
|
|
837
|
-
#
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
#
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
await asyncio.
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
"
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
startup_info.append("
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
:
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
:
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
'
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
settings = SettingManager()
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
settings
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
'
|
|
1099
|
-
'
|
|
1100
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawlo Crawler Module
|
|
5
|
+
====================
|
|
6
|
+
Provides crawler process management and runtime core functionality.
|
|
7
|
+
|
|
8
|
+
Core Components:
|
|
9
|
+
- Crawler: Single crawler runtime instance, managing Spider and engine lifecycle
|
|
10
|
+
- CrawlerProcess: Crawler process manager, supporting multi-crawler concurrent scheduling and resource management
|
|
11
|
+
|
|
12
|
+
Features:
|
|
13
|
+
- Intelligent concurrency control and resource management
|
|
14
|
+
- Graceful shutdown and signal handling
|
|
15
|
+
- Statistics monitoring and performance tracking
|
|
16
|
+
- Automatic module discovery and registration
|
|
17
|
+
- Error recovery and retry mechanism
|
|
18
|
+
- Large-scale crawler optimization support
|
|
19
|
+
|
|
20
|
+
Example Usage:
|
|
21
|
+
# Single crawler run
|
|
22
|
+
crawler = Crawler(MySpider, settings)
|
|
23
|
+
await crawler.crawl()
|
|
24
|
+
|
|
25
|
+
# Multi-crawler concurrent management
|
|
26
|
+
process = CrawlerProcess()
|
|
27
|
+
await process.crawl([Spider1, Spider2])
|
|
28
|
+
"""
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
import asyncio
|
|
31
|
+
import signal
|
|
32
|
+
import time
|
|
33
|
+
import threading
|
|
34
|
+
from typing import Type, Optional, Set, List, Union, Dict, Any
|
|
35
|
+
from .spider import Spider, get_global_spider_registry
|
|
36
|
+
from .core.engine import Engine
|
|
37
|
+
from .utils.log import get_logger
|
|
38
|
+
from .subscriber import Subscriber
|
|
39
|
+
from .extension import ExtensionManager
|
|
40
|
+
from .stats_collector import StatsCollector
|
|
41
|
+
from .event import spider_opened, spider_closed
|
|
42
|
+
from .settings.setting_manager import SettingManager
|
|
43
|
+
from crawlo.project import merge_settings, get_settings
|
|
44
|
+
|
|
45
|
+
# 延迟初始化logger,在需要时通过get_logger获取
|
|
46
|
+
logger = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _get_logger():
|
|
50
|
+
"""延迟获取logger实例,确保在配置加载后创建"""
|
|
51
|
+
global logger
|
|
52
|
+
if logger is None:
|
|
53
|
+
logger = get_logger(__name__)
|
|
54
|
+
return logger
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class CrawlerContext:
|
|
58
|
+
"""
|
|
59
|
+
Crawler context manager
|
|
60
|
+
Provides shared state and resource management
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self):
|
|
64
|
+
self.start_time = time.time()
|
|
65
|
+
self.total_crawlers = 0
|
|
66
|
+
self.active_crawlers = 0
|
|
67
|
+
self.completed_crawlers = 0
|
|
68
|
+
self.failed_crawlers = 0
|
|
69
|
+
self.error_log = []
|
|
70
|
+
self._lock = threading.RLock()
|
|
71
|
+
|
|
72
|
+
def increment_total(self):
|
|
73
|
+
with self._lock:
|
|
74
|
+
self.total_crawlers += 1
|
|
75
|
+
|
|
76
|
+
def increment_active(self):
|
|
77
|
+
with self._lock:
|
|
78
|
+
self.active_crawlers += 1
|
|
79
|
+
|
|
80
|
+
def decrement_active(self):
|
|
81
|
+
with self._lock:
|
|
82
|
+
self.active_crawlers -= 1
|
|
83
|
+
|
|
84
|
+
def increment_completed(self):
|
|
85
|
+
with self._lock:
|
|
86
|
+
self.completed_crawlers += 1
|
|
87
|
+
|
|
88
|
+
def increment_failed(self, error: str):
|
|
89
|
+
with self._lock:
|
|
90
|
+
self.failed_crawlers += 1
|
|
91
|
+
self.error_log.append({
|
|
92
|
+
'timestamp': time.time(),
|
|
93
|
+
'error': error
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
def get_stats(self) -> Dict[str, Any]:
|
|
97
|
+
with self._lock:
|
|
98
|
+
duration = time.time() - self.start_time
|
|
99
|
+
return {
|
|
100
|
+
'total_crawlers': self.total_crawlers,
|
|
101
|
+
'active_crawlers': self.active_crawlers,
|
|
102
|
+
'completed_crawlers': self.completed_crawlers,
|
|
103
|
+
'failed_crawlers': self.failed_crawlers,
|
|
104
|
+
'success_rate': (self.completed_crawlers / max(1, self.total_crawlers)) * 100,
|
|
105
|
+
'duration_seconds': round(duration, 2),
|
|
106
|
+
'error_count': len(self.error_log)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Crawler:
|
|
111
|
+
"""
|
|
112
|
+
Single crawler runtime instance, managing Spider and engine lifecycle
|
|
113
|
+
|
|
114
|
+
Provides functionality:
|
|
115
|
+
- Spider lifecycle management (initialization, running, closing)
|
|
116
|
+
- Engine component coordination management
|
|
117
|
+
- Configuration merging and validation
|
|
118
|
+
- Statistics data collection
|
|
119
|
+
- Extension management
|
|
120
|
+
- Exception handling and cleanup
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, spider_cls: Type[Spider], settings: SettingManager, context: Optional[CrawlerContext] = None):
|
|
124
|
+
self.spider_cls = spider_cls
|
|
125
|
+
self.spider: Optional[Spider] = None
|
|
126
|
+
self.engine: Optional[Engine] = None
|
|
127
|
+
self.stats: Optional[StatsCollector] = None
|
|
128
|
+
self.subscriber: Optional[Subscriber] = None
|
|
129
|
+
self.extension: Optional[ExtensionManager] = None
|
|
130
|
+
self.settings: SettingManager = settings.copy()
|
|
131
|
+
self.context = context or CrawlerContext()
|
|
132
|
+
|
|
133
|
+
# State management
|
|
134
|
+
self._closed = False
|
|
135
|
+
self._close_lock = asyncio.Lock()
|
|
136
|
+
self._start_time = None
|
|
137
|
+
self._end_time = None
|
|
138
|
+
|
|
139
|
+
# Performance monitoring
|
|
140
|
+
self._performance_metrics = {
|
|
141
|
+
'initialization_time': 0,
|
|
142
|
+
'crawl_duration': 0,
|
|
143
|
+
'memory_peak': 0,
|
|
144
|
+
'request_count': 0,
|
|
145
|
+
'error_count': 0
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async def crawl(self):
|
|
149
|
+
"""
|
|
150
|
+
Start the crawler core process
|
|
151
|
+
|
|
152
|
+
Includes the following stages:
|
|
153
|
+
1. Initialization stage: Create all components
|
|
154
|
+
2. Validation stage: Check configuration and state
|
|
155
|
+
3. Running stage: Start the crawler engine
|
|
156
|
+
4. Cleanup stage: Resource release
|
|
157
|
+
"""
|
|
158
|
+
init_start = time.time()
|
|
159
|
+
self._start_time = init_start
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
# Update context status
|
|
163
|
+
self.context.increment_active()
|
|
164
|
+
|
|
165
|
+
# Phase 1: Initialize components
|
|
166
|
+
# Adjust component initialization order to ensure log output order meets requirements
|
|
167
|
+
self.subscriber = self._create_subscriber()
|
|
168
|
+
self.spider = self._create_spider()
|
|
169
|
+
self.engine = self._create_engine()
|
|
170
|
+
self.stats = self._create_stats()
|
|
171
|
+
# Note: Do not initialize extension manager here, let it initialize in the engine
|
|
172
|
+
|
|
173
|
+
# Record initialization time
|
|
174
|
+
self._performance_metrics['initialization_time'] = time.time() - init_start
|
|
175
|
+
|
|
176
|
+
# Phase 2: Validate state
|
|
177
|
+
self._validate_crawler_state()
|
|
178
|
+
|
|
179
|
+
# Phase 3: Display runtime configuration summary
|
|
180
|
+
self._log_runtime_summary()
|
|
181
|
+
|
|
182
|
+
# Phase 4: Start crawler
|
|
183
|
+
crawl_start = time.time()
|
|
184
|
+
await self.engine.start_spider(self.spider)
|
|
185
|
+
|
|
186
|
+
# Record crawl time
|
|
187
|
+
self._performance_metrics['crawl_duration'] = time.time() - crawl_start
|
|
188
|
+
self._end_time = time.time()
|
|
189
|
+
|
|
190
|
+
# Update context status
|
|
191
|
+
self.context.increment_completed()
|
|
192
|
+
|
|
193
|
+
_get_logger().info(f"Spider {self.spider.name} completed, took {self._get_total_duration():.2f} seconds")
|
|
194
|
+
|
|
195
|
+
except Exception as e:
|
|
196
|
+
self._performance_metrics['error_count'] += 1
|
|
197
|
+
self.context.increment_failed(str(e))
|
|
198
|
+
_get_logger().error(f"Spider {getattr(self.spider, 'name', 'Unknown')} failed to run: {e}", exc_info=True)
|
|
199
|
+
raise
|
|
200
|
+
finally:
|
|
201
|
+
self.context.decrement_active()
|
|
202
|
+
# Ensure resource cleanup
|
|
203
|
+
await self._ensure_cleanup()
|
|
204
|
+
|
|
205
|
+
def _log_runtime_summary(self):
|
|
206
|
+
"""Log runtime configuration summary"""
|
|
207
|
+
# Get spider name
|
|
208
|
+
spider_name = getattr(self.spider, 'name', 'Unknown')
|
|
209
|
+
|
|
210
|
+
# Ensure spider name is a string and strip leading/trailing whitespace
|
|
211
|
+
if spider_name:
|
|
212
|
+
spider_name = str(spider_name).strip()
|
|
213
|
+
else:
|
|
214
|
+
spider_name = 'Unknown'
|
|
215
|
+
|
|
216
|
+
_get_logger().info(f"Starting running {spider_name}")
|
|
217
|
+
|
|
218
|
+
def _validate_crawler_state(self):
|
|
219
|
+
"""
|
|
220
|
+
Validate crawler state and configuration
|
|
221
|
+
Ensure all necessary components are properly initialized
|
|
222
|
+
"""
|
|
223
|
+
if not self.spider:
|
|
224
|
+
raise RuntimeError("Spider instance not initialized")
|
|
225
|
+
if not self.engine:
|
|
226
|
+
raise RuntimeError("Engine not initialized")
|
|
227
|
+
if not self.stats:
|
|
228
|
+
raise RuntimeError("Stats collector not initialized")
|
|
229
|
+
if not self.subscriber:
|
|
230
|
+
raise RuntimeError("Event subscriber not initialized")
|
|
231
|
+
|
|
232
|
+
# Check key configuration
|
|
233
|
+
if not self.spider.name:
|
|
234
|
+
raise ValueError("Spider name cannot be empty")
|
|
235
|
+
|
|
236
|
+
_get_logger().debug(f"Spider {self.spider.name} state validation passed")
|
|
237
|
+
|
|
238
|
+
def _get_total_duration(self) -> float:
|
|
239
|
+
"""Get total runtime"""
|
|
240
|
+
if self._start_time and self._end_time:
|
|
241
|
+
return self._end_time - self._start_time
|
|
242
|
+
return 0.0
|
|
243
|
+
|
|
244
|
+
async def _ensure_cleanup(self):
|
|
245
|
+
"""Ensure resource cleanup"""
|
|
246
|
+
try:
|
|
247
|
+
if not self._closed:
|
|
248
|
+
await self.close()
|
|
249
|
+
except Exception as e:
|
|
250
|
+
_get_logger().warning(f"Error cleaning up resources: {e}")
|
|
251
|
+
|
|
252
|
+
def get_performance_metrics(self) -> Dict[str, Any]:
|
|
253
|
+
"""Get performance metrics"""
|
|
254
|
+
metrics = self._performance_metrics.copy()
|
|
255
|
+
metrics['total_duration'] = self._get_total_duration()
|
|
256
|
+
if self.stats:
|
|
257
|
+
# Add statistics data
|
|
258
|
+
stats_data = getattr(self.stats, 'get_stats', lambda: {})()
|
|
259
|
+
metrics.update(stats_data)
|
|
260
|
+
return metrics
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def _create_subscriber() -> Subscriber:
|
|
264
|
+
"""Create event subscriber"""
|
|
265
|
+
return Subscriber()
|
|
266
|
+
|
|
267
|
+
def _create_spider(self) -> Spider:
|
|
268
|
+
"""
|
|
269
|
+
Create and validate spider instance (enhanced version)
|
|
270
|
+
|
|
271
|
+
Performs the following validations:
|
|
272
|
+
- Spider name must exist
|
|
273
|
+
- start_requests method must be callable
|
|
274
|
+
- start_urls cannot be a string
|
|
275
|
+
- parse method is recommended to exist
|
|
276
|
+
"""
|
|
277
|
+
spider = self.spider_cls.create_instance(self)
|
|
278
|
+
|
|
279
|
+
# Required attribute check
|
|
280
|
+
if not getattr(spider, 'name', None):
|
|
281
|
+
raise AttributeError(
|
|
282
|
+
f"Spider class '{self.spider_cls.__name__}' must define 'name' attribute.\n"
|
|
283
|
+
f"Example: name = 'my_spider'"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
if not callable(getattr(spider, 'start_requests', None)):
|
|
287
|
+
raise AttributeError(
|
|
288
|
+
f"Spider '{spider.name}' must implement a callable 'start_requests' method.\n"
|
|
289
|
+
f"Example: def start_requests(self): yield Request(url='...')"
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
# start_urls type check
|
|
293
|
+
start_urls = getattr(spider, 'start_urls', [])
|
|
294
|
+
if isinstance(start_urls, str):
|
|
295
|
+
raise TypeError(
|
|
296
|
+
f"Spider '{spider.name}' 'start_urls' must be a list or tuple, not a string.\n"
|
|
297
|
+
f"Correct: start_urls = ['http://example.com']\n"
|
|
298
|
+
f"Incorrect: start_urls = 'http://example.com'"
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
# parse method check (warning instead of error)
|
|
302
|
+
if not callable(getattr(spider, 'parse', None)):
|
|
303
|
+
_get_logger().warning(
|
|
304
|
+
f"Spider '{spider.name}' does not define 'parse' method.\n"
|
|
305
|
+
f"Ensure all Requests specify a callback function, otherwise responses will be ignored."
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
# Set spider configuration
|
|
309
|
+
self._set_spider(spider)
|
|
310
|
+
|
|
311
|
+
_get_logger().debug(f"Spider '{spider.name}' initialized successfully")
|
|
312
|
+
return spider
|
|
313
|
+
|
|
314
|
+
def _create_engine(self) -> Engine:
|
|
315
|
+
"""Create and initialize engine"""
|
|
316
|
+
engine = Engine(self)
|
|
317
|
+
engine.engine_start()
|
|
318
|
+
_get_logger().debug(f"Engine initialized successfully, spider: {getattr(self.spider, 'name', 'Unknown')}")
|
|
319
|
+
return engine
|
|
320
|
+
|
|
321
|
+
def _create_stats(self) -> StatsCollector:
|
|
322
|
+
"""Create stats collector"""
|
|
323
|
+
stats = StatsCollector(self)
|
|
324
|
+
_get_logger().debug(f"Stats collector initialized successfully, spider: {getattr(self.spider, 'name', 'Unknown')}")
|
|
325
|
+
return stats
|
|
326
|
+
|
|
327
|
+
def _create_extension(self) -> ExtensionManager:
|
|
328
|
+
"""Create extension manager"""
|
|
329
|
+
# Modify extension manager creation method, delay initialization until needed
|
|
330
|
+
extension = ExtensionManager.create_instance(self)
|
|
331
|
+
_get_logger().debug(f"Extension manager initialized successfully, spider: {getattr(self.spider, 'name', 'Unknown')}")
|
|
332
|
+
return extension
|
|
333
|
+
|
|
334
|
+
def _set_spider(self, spider: Spider):
|
|
335
|
+
"""
|
|
336
|
+
Set spider configuration and event subscription
|
|
337
|
+
Bind spider lifecycle events with subscriber
|
|
338
|
+
"""
|
|
339
|
+
# Subscribe to spider lifecycle events
|
|
340
|
+
self.subscriber.subscribe(spider.spider_opened, event=spider_opened)
|
|
341
|
+
self.subscriber.subscribe(spider.spider_closed, event=spider_closed)
|
|
342
|
+
|
|
343
|
+
# Merge spider custom configuration
|
|
344
|
+
merge_settings(spider, self.settings)
|
|
345
|
+
|
|
346
|
+
_get_logger().debug(f"Spider '{spider.name}' configuration merged successfully")
|
|
347
|
+
|
|
348
|
+
async def close(self, reason='finished') -> None:
|
|
349
|
+
"""
|
|
350
|
+
Close crawler and clean up resources (enhanced version)
|
|
351
|
+
|
|
352
|
+
Ensure closing only once and handle all cleanup operations
|
|
353
|
+
"""
|
|
354
|
+
async with self._close_lock:
|
|
355
|
+
if self._closed:
|
|
356
|
+
return
|
|
357
|
+
|
|
358
|
+
self._closed = True
|
|
359
|
+
self._end_time = time.time()
|
|
360
|
+
|
|
361
|
+
try:
|
|
362
|
+
# Notify spider close event
|
|
363
|
+
if self.subscriber:
|
|
364
|
+
await self.subscriber.notify(spider_closed)
|
|
365
|
+
|
|
366
|
+
# Statistics data collection
|
|
367
|
+
if self.stats and self.spider:
|
|
368
|
+
self.stats.close_spider(spider=self.spider, reason=reason)
|
|
369
|
+
# Record statistics data
|
|
370
|
+
try:
|
|
371
|
+
from crawlo.commands.stats import record_stats
|
|
372
|
+
record_stats(self)
|
|
373
|
+
except ImportError:
|
|
374
|
+
_get_logger().debug("Statistics recording module does not exist, skipping statistics recording")
|
|
375
|
+
|
|
376
|
+
_get_logger().info(
|
|
377
|
+
f"Spider '{getattr(self.spider, 'name', 'Unknown')}' closed, "
|
|
378
|
+
f"reason: {reason}, took: {self._get_total_duration():.2f} seconds"
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
except Exception as e:
|
|
382
|
+
_get_logger().error(f"Error closing crawler: {e}", exc_info=True)
|
|
383
|
+
finally:
|
|
384
|
+
# Ensure resource cleanup
|
|
385
|
+
await self._cleanup_resources()
|
|
386
|
+
|
|
387
|
+
async def _cleanup_resources(self):
|
|
388
|
+
"""Clean up all resources"""
|
|
389
|
+
cleanup_tasks = []
|
|
390
|
+
|
|
391
|
+
# Engine cleanup
|
|
392
|
+
if self.engine:
|
|
393
|
+
try:
|
|
394
|
+
cleanup_tasks.append(self.engine.close())
|
|
395
|
+
except AttributeError:
|
|
396
|
+
pass # Engine has no close method
|
|
397
|
+
|
|
398
|
+
# Extension cleanup
|
|
399
|
+
if self.extension:
|
|
400
|
+
try:
|
|
401
|
+
cleanup_tasks.append(self.extension.close())
|
|
402
|
+
except AttributeError:
|
|
403
|
+
pass
|
|
404
|
+
|
|
405
|
+
# Stats collector cleanup
|
|
406
|
+
if self.stats:
|
|
407
|
+
try:
|
|
408
|
+
cleanup_tasks.append(self.stats.close())
|
|
409
|
+
except AttributeError:
|
|
410
|
+
pass
|
|
411
|
+
|
|
412
|
+
# Concurrently execute cleanup tasks
|
|
413
|
+
if cleanup_tasks:
|
|
414
|
+
await asyncio.gather(*cleanup_tasks, return_exceptions=True)
|
|
415
|
+
|
|
416
|
+
_get_logger().debug("Resource cleanup completed")
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
class CrawlerProcess:
|
|
420
|
+
"""
|
|
421
|
+
Crawler process manager
|
|
422
|
+
|
|
423
|
+
Supported features:
|
|
424
|
+
- Multi-crawler concurrent scheduling and resource management
|
|
425
|
+
- Automatic module discovery and spider registration
|
|
426
|
+
- Intelligent concurrency control and load balancing
|
|
427
|
+
- Graceful shutdown and signal handling
|
|
428
|
+
- Real-time status monitoring and statistics
|
|
429
|
+
- Error recovery and retry mechanism
|
|
430
|
+
- Large-scale crawler optimization support
|
|
431
|
+
|
|
432
|
+
Usage example:
|
|
433
|
+
# Basic usage
|
|
434
|
+
process = CrawlerProcess()
|
|
435
|
+
await process.crawl(MySpider)
|
|
436
|
+
|
|
437
|
+
# Multi-crawler concurrency
|
|
438
|
+
await process.crawl([Spider1, Spider2, 'spider_name'])
|
|
439
|
+
|
|
440
|
+
# Custom concurrency
|
|
441
|
+
process = CrawlerProcess(max_concurrency=8)
|
|
442
|
+
"""
|
|
443
|
+
|
|
444
|
+
def __init__(
|
|
445
|
+
self,
|
|
446
|
+
settings: Optional[SettingManager] = None,
|
|
447
|
+
max_concurrency: Optional[int] = None,
|
|
448
|
+
spider_modules: Optional[List[str]] = None,
|
|
449
|
+
enable_monitoring: bool = True
|
|
450
|
+
):
|
|
451
|
+
# Basic configuration
|
|
452
|
+
self.settings: SettingManager = settings or self._get_default_settings()
|
|
453
|
+
self.crawlers: Set[Crawler] = set()
|
|
454
|
+
self._active_tasks: Set[asyncio.Task] = set()
|
|
455
|
+
|
|
456
|
+
# Context manager
|
|
457
|
+
self.context = CrawlerContext()
|
|
458
|
+
|
|
459
|
+
# Concurrency control configuration
|
|
460
|
+
self.max_concurrency: int = (
|
|
461
|
+
max_concurrency
|
|
462
|
+
or self.settings.get('MAX_RUNNING_SPIDERS')
|
|
463
|
+
or self.settings.get('CONCURRENCY', 3)
|
|
464
|
+
)
|
|
465
|
+
self.semaphore = asyncio.Semaphore(self.max_concurrency)
|
|
466
|
+
|
|
467
|
+
# Monitoring configuration
|
|
468
|
+
self.enable_monitoring = enable_monitoring
|
|
469
|
+
self._monitoring_task = None
|
|
470
|
+
self._shutdown_event = asyncio.Event()
|
|
471
|
+
|
|
472
|
+
# Automatically discover and import spider modules
|
|
473
|
+
if spider_modules:
|
|
474
|
+
self.auto_discover(spider_modules)
|
|
475
|
+
|
|
476
|
+
# Use snapshot of global registry (avoid subsequent import impact)
|
|
477
|
+
self._spider_registry: Dict[str, Type[Spider]] = get_global_spider_registry()
|
|
478
|
+
|
|
479
|
+
# Performance monitoring
|
|
480
|
+
self._performance_stats = {
|
|
481
|
+
'total_requests': 0,
|
|
482
|
+
'successful_requests': 0,
|
|
483
|
+
'failed_requests': 0,
|
|
484
|
+
'memory_usage_mb': 0,
|
|
485
|
+
'cpu_usage_percent': 0
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
# Register signal handlers
|
|
489
|
+
signal.signal(signal.SIGINT, self._shutdown)
|
|
490
|
+
signal.signal(signal.SIGTERM, self._shutdown)
|
|
491
|
+
|
|
492
|
+
self._log_startup_info()
|
|
493
|
+
|
|
494
|
+
logger.debug(
|
|
495
|
+
f"CrawlerProcess initialized successfully\n"
|
|
496
|
+
f" - Max concurrent crawlers: {self.max_concurrency}\n"
|
|
497
|
+
f" - Registered crawlers: {len(self._spider_registry)}\n"
|
|
498
|
+
f" - Monitoring enabled: {self.enable_monitoring}"
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
async def start_monitoring(self):
|
|
502
|
+
"""Start monitoring task"""
|
|
503
|
+
if not self.enable_monitoring:
|
|
504
|
+
return
|
|
505
|
+
|
|
506
|
+
self._monitoring_task = asyncio.create_task(self._monitor_loop())
|
|
507
|
+
logger.debug("Monitoring task started")
|
|
508
|
+
|
|
509
|
+
async def stop_monitoring(self):
|
|
510
|
+
"""Stop monitoring task"""
|
|
511
|
+
if self._monitoring_task and not self._monitoring_task.done():
|
|
512
|
+
self._monitoring_task.cancel()
|
|
513
|
+
try:
|
|
514
|
+
await self._monitoring_task
|
|
515
|
+
except asyncio.CancelledError:
|
|
516
|
+
pass
|
|
517
|
+
logger.debug("Monitoring task stopped")
|
|
518
|
+
|
|
519
|
+
async def _monitor_loop(self):
|
|
520
|
+
"""Monitoring loop, periodically collect and report status"""
|
|
521
|
+
try:
|
|
522
|
+
while not self._shutdown_event.is_set():
|
|
523
|
+
await self._collect_performance_stats()
|
|
524
|
+
|
|
525
|
+
# Output status every 30 seconds
|
|
526
|
+
stats = self.context.get_stats()
|
|
527
|
+
if stats['active_crawlers'] > 0:
|
|
528
|
+
logger.debug(
|
|
529
|
+
f"Crawler status: Active {stats['active_crawlers']}, "
|
|
530
|
+
f"Completed {stats['completed_crawlers']}, "
|
|
531
|
+
f"Failed {stats['failed_crawlers']}, "
|
|
532
|
+
f"Success rate {stats['success_rate']:.1f}%"
|
|
533
|
+
)
|
|
534
|
+
|
|
535
|
+
await asyncio.sleep(30) # 30 second interval
|
|
536
|
+
|
|
537
|
+
except asyncio.CancelledError:
|
|
538
|
+
logger.debug("Monitoring loop cancelled")
|
|
539
|
+
except Exception as e:
|
|
540
|
+
logger.error(f"Monitoring loop error: {e}", exc_info=True)
|
|
541
|
+
|
|
542
|
+
async def _collect_performance_stats(self):
|
|
543
|
+
"""Collect performance statistics data"""
|
|
544
|
+
try:
|
|
545
|
+
import psutil
|
|
546
|
+
import os
|
|
547
|
+
|
|
548
|
+
process = psutil.Process(os.getpid())
|
|
549
|
+
memory_info = process.memory_info()
|
|
550
|
+
|
|
551
|
+
self._performance_stats.update({
|
|
552
|
+
'memory_usage_mb': round(memory_info.rss / 1024 / 1024, 2),
|
|
553
|
+
'cpu_usage_percent': round(process.cpu_percent(), 2)
|
|
554
|
+
})
|
|
555
|
+
|
|
556
|
+
except ImportError:
|
|
557
|
+
# Skip performance monitoring when psutil is not available
|
|
558
|
+
pass
|
|
559
|
+
except Exception as e:
|
|
560
|
+
logger.debug(f"Failed to collect performance statistics: {e}")
|
|
561
|
+
|
|
562
|
+
@staticmethod
|
|
563
|
+
def auto_discover(modules: List[str]):
|
|
564
|
+
"""
|
|
565
|
+
Automatically import modules, trigger Spider class definition and registration (enhanced version)
|
|
566
|
+
|
|
567
|
+
Supports recursive scanning and error recovery
|
|
568
|
+
"""
|
|
569
|
+
import importlib
|
|
570
|
+
import pkgutil
|
|
571
|
+
|
|
572
|
+
discovered_count = 0
|
|
573
|
+
error_count = 0
|
|
574
|
+
|
|
575
|
+
for module_name in modules:
|
|
576
|
+
try:
|
|
577
|
+
module = importlib.import_module(module_name)
|
|
578
|
+
|
|
579
|
+
if hasattr(module, '__path__'):
|
|
580
|
+
# Package module, recursive scanning
|
|
581
|
+
for _, name, _ in pkgutil.walk_packages(module.__path__, module.__name__ + "."):
|
|
582
|
+
try:
|
|
583
|
+
importlib.import_module(name)
|
|
584
|
+
discovered_count += 1
|
|
585
|
+
except Exception as sub_e:
|
|
586
|
+
error_count += 1
|
|
587
|
+
logger.warning(f"Failed to import submodule {name}: {sub_e}")
|
|
588
|
+
else:
|
|
589
|
+
# Single module
|
|
590
|
+
importlib.import_module(module_name)
|
|
591
|
+
discovered_count += 1
|
|
592
|
+
|
|
593
|
+
logger.debug(f"Module scanned: {module_name}")
|
|
594
|
+
|
|
595
|
+
except Exception as e:
|
|
596
|
+
error_count += 1
|
|
597
|
+
logger.error(f"Failed to scan module {module_name}: {e}", exc_info=True)
|
|
598
|
+
|
|
599
|
+
logger.debug(
|
|
600
|
+
f"Spider registration completed: {discovered_count} succeeded, {error_count} failed"
|
|
601
|
+
)
|
|
602
|
+
|
|
603
|
+
# === Public read-only interface: Avoid direct access to _spider_registry ===
|
|
604
|
+
|
|
605
|
+
def get_spider_names(self) -> List[str]:
|
|
606
|
+
"""Get all registered spider names"""
|
|
607
|
+
return list(self._spider_registry.keys())
|
|
608
|
+
|
|
609
|
+
def get_spider_class(self, name: str) -> Optional[Type[Spider]]:
|
|
610
|
+
"""Get spider class by name"""
|
|
611
|
+
return self._spider_registry.get(name)
|
|
612
|
+
|
|
613
|
+
def is_spider_registered(self, name: str) -> bool:
|
|
614
|
+
"""Check if a name is registered"""
|
|
615
|
+
return name in self._spider_registry
|
|
616
|
+
|
|
617
|
+
async def crawl(self, spiders: Union[Type[Spider], str, List[Union[Type[Spider], str]]]):
|
|
618
|
+
"""
|
|
619
|
+
Start one or more crawlers
|
|
620
|
+
|
|
621
|
+
Enhanced features:
|
|
622
|
+
- Intelligent concurrency control
|
|
623
|
+
- Real-time monitoring and statistics
|
|
624
|
+
- Error recovery and retry
|
|
625
|
+
- Graceful shutdown handling
|
|
626
|
+
"""
|
|
627
|
+
# Phase 1: Preprocessing and validation
|
|
628
|
+
spider_classes_to_run = self._resolve_spiders_to_run(spiders)
|
|
629
|
+
total = len(spider_classes_to_run)
|
|
630
|
+
|
|
631
|
+
if total == 0:
|
|
632
|
+
raise ValueError("At least one spider class or name must be provided")
|
|
633
|
+
|
|
634
|
+
# Phase 2: Initialize context and monitoring
|
|
635
|
+
for _ in range(total):
|
|
636
|
+
self.context.increment_total()
|
|
637
|
+
|
|
638
|
+
# Start monitoring task
|
|
639
|
+
await self.start_monitoring()
|
|
640
|
+
|
|
641
|
+
try:
|
|
642
|
+
# Phase 3: Sort by class name to ensure predictable startup order
|
|
643
|
+
spider_classes_to_run.sort(key=lambda cls: cls.__name__.lower())
|
|
644
|
+
|
|
645
|
+
logger.debug(
|
|
646
|
+
f"Starting {total} crawlers\n"
|
|
647
|
+
f" - Max concurrency: {self.max_concurrency}\n"
|
|
648
|
+
f" - Spider list: {[cls.__name__ for cls in spider_classes_to_run]}"
|
|
649
|
+
)
|
|
650
|
+
|
|
651
|
+
# Phase 4: Stream start all crawler tasks
|
|
652
|
+
tasks = [
|
|
653
|
+
asyncio.create_task(
|
|
654
|
+
self._run_spider_with_limit(spider_cls, index + 1, total),
|
|
655
|
+
name=f"spider-{spider_cls.__name__}-{index + 1}"
|
|
656
|
+
)
|
|
657
|
+
for index, spider_cls in enumerate(spider_classes_to_run)
|
|
658
|
+
]
|
|
659
|
+
|
|
660
|
+
# Phase 5: Wait for all tasks to complete (failures do not interrupt)
|
|
661
|
+
results = await asyncio.gather(*tasks, return_exceptions=True)
|
|
662
|
+
|
|
663
|
+
# Phase 6: Statistics exceptions and results
|
|
664
|
+
failed = [i for i, r in enumerate(results) if isinstance(r, Exception)]
|
|
665
|
+
successful = total - len(failed)
|
|
666
|
+
|
|
667
|
+
if failed:
|
|
668
|
+
failed_spiders = [spider_classes_to_run[i].__name__ for i in failed]
|
|
669
|
+
logger.error(
|
|
670
|
+
f"Crawler execution result: {successful}/{total} succeeded, {len(failed)}/{total} failed\n"
|
|
671
|
+
f" - Failed crawlers: {failed_spiders}"
|
|
672
|
+
)
|
|
673
|
+
|
|
674
|
+
# Record detailed error information
|
|
675
|
+
for i in failed:
|
|
676
|
+
error = results[i]
|
|
677
|
+
logger.error(f"Spider {spider_classes_to_run[i].__name__} error details: {error}")
|
|
678
|
+
else:
|
|
679
|
+
logger.info(f"All {total} crawlers completed successfully!")
|
|
680
|
+
|
|
681
|
+
# Return statistics results
|
|
682
|
+
return {
|
|
683
|
+
'total': total,
|
|
684
|
+
'successful': successful,
|
|
685
|
+
'failed': len(failed),
|
|
686
|
+
'success_rate': (successful / total) * 100 if total > 0 else 0,
|
|
687
|
+
'context_stats': self.context.get_stats()
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
finally:
|
|
691
|
+
# Phase 7: Cleanup and shutdown
|
|
692
|
+
await self.stop_monitoring()
|
|
693
|
+
await self._cleanup_process()
|
|
694
|
+
|
|
695
|
+
async def _cleanup_process(self):
|
|
696
|
+
"""Clean up process resources"""
|
|
697
|
+
try:
|
|
698
|
+
# Wait for all active crawlers to complete
|
|
699
|
+
if self.crawlers:
|
|
700
|
+
close_tasks = [crawler.close() for crawler in self.crawlers]
|
|
701
|
+
await asyncio.gather(*close_tasks, return_exceptions=True)
|
|
702
|
+
self.crawlers.clear()
|
|
703
|
+
|
|
704
|
+
# Clean up active tasks
|
|
705
|
+
if self._active_tasks:
|
|
706
|
+
for task in list(self._active_tasks):
|
|
707
|
+
if not task.done():
|
|
708
|
+
task.cancel()
|
|
709
|
+
await asyncio.gather(*self._active_tasks, return_exceptions=True)
|
|
710
|
+
self._active_tasks.clear()
|
|
711
|
+
|
|
712
|
+
logger.debug("Process resources cleanup completed")
|
|
713
|
+
|
|
714
|
+
except Exception as e:
|
|
715
|
+
logger.error(f"Error cleaning up process resources: {e}", exc_info=True)
|
|
716
|
+
|
|
717
|
+
def get_process_stats(self) -> Dict[str, Any]:
|
|
718
|
+
"""Get process statistics information"""
|
|
719
|
+
context_stats = self.context.get_stats()
|
|
720
|
+
|
|
721
|
+
return {
|
|
722
|
+
'context': context_stats,
|
|
723
|
+
'performance': self._performance_stats.copy(),
|
|
724
|
+
'crawlers': {
|
|
725
|
+
'total_registered': len(self._spider_registry),
|
|
726
|
+
'active_crawlers': len(self.crawlers),
|
|
727
|
+
'max_concurrency': self.max_concurrency
|
|
728
|
+
},
|
|
729
|
+
'registry': {
|
|
730
|
+
'spider_names': list(self._spider_registry.keys()),
|
|
731
|
+
'spider_classes': [cls.__name__ for cls in self._spider_registry.values()]
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
def _resolve_spiders_to_run(
|
|
736
|
+
self,
|
|
737
|
+
spiders_input: Union[Type[Spider], str, List[Union[Type[Spider], str]]]
|
|
738
|
+
) -> List[Type[Spider]]:
|
|
739
|
+
"""
|
|
740
|
+
Resolve input to spider class list
|
|
741
|
+
|
|
742
|
+
Supports various input formats and validates uniqueness
|
|
743
|
+
"""
|
|
744
|
+
inputs = self._normalize_inputs(spiders_input)
|
|
745
|
+
seen_spider_names: Set[str] = set()
|
|
746
|
+
spider_classes: List[Type[Spider]] = []
|
|
747
|
+
|
|
748
|
+
for item in inputs:
|
|
749
|
+
try:
|
|
750
|
+
spider_cls = self._resolve_spider_class(item)
|
|
751
|
+
spider_name = getattr(spider_cls, 'name', None)
|
|
752
|
+
|
|
753
|
+
if not spider_name:
|
|
754
|
+
raise ValueError(f"Spider class {spider_cls.__name__} missing 'name' attribute")
|
|
755
|
+
|
|
756
|
+
if spider_name in seen_spider_names:
|
|
757
|
+
raise ValueError(
|
|
758
|
+
f"Duplicate spider name '{spider_name}' in this run.\n"
|
|
759
|
+
f"Ensure each spider's name attribute is unique in this run."
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
seen_spider_names.add(spider_name)
|
|
763
|
+
spider_classes.append(spider_cls)
|
|
764
|
+
|
|
765
|
+
logger.debug(f"Spider resolved successfully: {item} -> {spider_cls.__name__} (name='{spider_name}')")
|
|
766
|
+
|
|
767
|
+
except Exception as e:
|
|
768
|
+
logger.error(f"Failed to resolve spider: {item} - {e}")
|
|
769
|
+
raise
|
|
770
|
+
|
|
771
|
+
return spider_classes
|
|
772
|
+
|
|
773
|
+
@staticmethod
|
|
774
|
+
def _normalize_inputs(spiders_input) -> List[Union[Type[Spider], str]]:
|
|
775
|
+
"""
|
|
776
|
+
Normalize input to list
|
|
777
|
+
|
|
778
|
+
Supports more input types and provides better error information
|
|
779
|
+
"""
|
|
780
|
+
if isinstance(spiders_input, (type, str)):
|
|
781
|
+
return [spiders_input]
|
|
782
|
+
elif isinstance(spiders_input, (list, tuple, set)):
|
|
783
|
+
spider_list = list(spiders_input)
|
|
784
|
+
if not spider_list:
|
|
785
|
+
raise ValueError("Spider list cannot be empty")
|
|
786
|
+
return spider_list
|
|
787
|
+
else:
|
|
788
|
+
raise TypeError(
|
|
789
|
+
f"Unsupported spiders parameter type: {type(spiders_input)}\n"
|
|
790
|
+
f"Supported types: Spider class, name string, or their list/tuple/set"
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
def _resolve_spider_class(self, item: Union[Type[Spider], str]) -> Type[Spider]:
|
|
794
|
+
"""
|
|
795
|
+
Resolve single input item to spider class
|
|
796
|
+
|
|
797
|
+
Provides better error prompts and debugging information
|
|
798
|
+
"""
|
|
799
|
+
if isinstance(item, type) and issubclass(item, Spider):
|
|
800
|
+
# Direct Spider class
|
|
801
|
+
return item
|
|
802
|
+
elif isinstance(item, str):
|
|
803
|
+
# String name, need to look up registry
|
|
804
|
+
spider_cls = self._spider_registry.get(item)
|
|
805
|
+
if not spider_cls:
|
|
806
|
+
available_spiders = list(self._spider_registry.keys())
|
|
807
|
+
raise ValueError(
|
|
808
|
+
f"Spider named '{item}' not found.\n"
|
|
809
|
+
f"Registered spiders: {available_spiders}\n"
|
|
810
|
+
f"Please check if the spider name is correct, or ensure the spider has been properly imported and registered."
|
|
811
|
+
)
|
|
812
|
+
return spider_cls
|
|
813
|
+
else:
|
|
814
|
+
raise TypeError(
|
|
815
|
+
f"Invalid type {type(item)}: {item}\n"
|
|
816
|
+
f"Must be Spider class or string name.\n"
|
|
817
|
+
f"Example: MySpider or 'my_spider'"
|
|
818
|
+
)
|
|
819
|
+
|
|
820
|
+
async def _run_spider_with_limit(self, spider_cls: Type[Spider], seq: int, total: int):
|
|
821
|
+
"""
|
|
822
|
+
Spider running function limited by semaphore
|
|
823
|
+
|
|
824
|
+
Includes enhanced error handling and monitoring functionality
|
|
825
|
+
"""
|
|
826
|
+
task = asyncio.current_task()
|
|
827
|
+
crawler = None
|
|
828
|
+
|
|
829
|
+
try:
|
|
830
|
+
# Register task
|
|
831
|
+
if task:
|
|
832
|
+
self._active_tasks.add(task)
|
|
833
|
+
|
|
834
|
+
# Acquire concurrency permit
|
|
835
|
+
await self.semaphore.acquire()
|
|
836
|
+
|
|
837
|
+
# start_msg = f"[{seq}/{total}] Initializing spider: {spider_cls.__name__}"
|
|
838
|
+
# logger.info(start_msg)
|
|
839
|
+
|
|
840
|
+
# Create and run crawler
|
|
841
|
+
crawler = Crawler(spider_cls, self.settings, self.context)
|
|
842
|
+
self.crawlers.add(crawler)
|
|
843
|
+
|
|
844
|
+
# Record start time
|
|
845
|
+
start_time = time.time()
|
|
846
|
+
|
|
847
|
+
# Run crawler
|
|
848
|
+
await crawler.crawl()
|
|
849
|
+
|
|
850
|
+
# Calculate runtime
|
|
851
|
+
duration = time.time() - start_time
|
|
852
|
+
|
|
853
|
+
end_msg = (
|
|
854
|
+
f"[{seq}/{total}] Crawler completed: {spider_cls.__name__}, "
|
|
855
|
+
f"took: {duration:.2f} seconds"
|
|
856
|
+
)
|
|
857
|
+
logger.info(end_msg)
|
|
858
|
+
|
|
859
|
+
# Record success statistics
|
|
860
|
+
self._performance_stats['successful_requests'] += 1
|
|
861
|
+
|
|
862
|
+
except Exception as e:
|
|
863
|
+
# Record failure statistics
|
|
864
|
+
self._performance_stats['failed_requests'] += 1
|
|
865
|
+
|
|
866
|
+
error_msg = f"Spider {spider_cls.__name__} execution failed: {e}"
|
|
867
|
+
logger.error(error_msg, exc_info=True)
|
|
868
|
+
|
|
869
|
+
# Record error information to context
|
|
870
|
+
if hasattr(self, 'context'):
|
|
871
|
+
self.context.increment_failed(error_msg)
|
|
872
|
+
|
|
873
|
+
raise
|
|
874
|
+
finally:
|
|
875
|
+
# Clean up resources
|
|
876
|
+
try:
|
|
877
|
+
if crawler and crawler in self.crawlers:
|
|
878
|
+
self.crawlers.remove(crawler)
|
|
879
|
+
|
|
880
|
+
if task and task in self._active_tasks:
|
|
881
|
+
self._active_tasks.remove(task)
|
|
882
|
+
|
|
883
|
+
self.semaphore.release()
|
|
884
|
+
|
|
885
|
+
except Exception as cleanup_error:
|
|
886
|
+
logger.warning(f"Error cleaning up resources: {cleanup_error}")
|
|
887
|
+
|
|
888
|
+
def _shutdown(self, _signum, _frame):
|
|
889
|
+
"""
|
|
890
|
+
Graceful shutdown signal handling
|
|
891
|
+
|
|
892
|
+
Provides better shutdown experience and resource cleanup
|
|
893
|
+
"""
|
|
894
|
+
signal_name = {signal.SIGINT: 'SIGINT', signal.SIGTERM: 'SIGTERM'}.get(_signum, str(_signum))
|
|
895
|
+
logger.warning(f"Received shutdown signal {signal_name}, stopping all crawlers...")
|
|
896
|
+
|
|
897
|
+
# Set shutdown event
|
|
898
|
+
if hasattr(self, '_shutdown_event'):
|
|
899
|
+
self._shutdown_event.set()
|
|
900
|
+
|
|
901
|
+
# Stop all crawler engines
|
|
902
|
+
for crawler in list(self.crawlers):
|
|
903
|
+
if crawler.engine:
|
|
904
|
+
crawler.engine.running = False
|
|
905
|
+
crawler.engine.normal = False
|
|
906
|
+
logger.debug(f"Crawler engine stopped: {getattr(crawler.spider, 'name', 'Unknown')}")
|
|
907
|
+
|
|
908
|
+
# Create shutdown task
|
|
909
|
+
asyncio.create_task(self._wait_for_shutdown())
|
|
910
|
+
|
|
911
|
+
logger.info("Shutdown command sent, waiting for crawlers to complete current tasks...")
|
|
912
|
+
|
|
913
|
+
async def _wait_for_shutdown(self):
|
|
914
|
+
"""
|
|
915
|
+
Wait for all active tasks to complete
|
|
916
|
+
|
|
917
|
+
Provides better shutdown time control and progress feedback
|
|
918
|
+
"""
|
|
919
|
+
try:
|
|
920
|
+
# Stop monitoring task
|
|
921
|
+
await self.stop_monitoring()
|
|
922
|
+
|
|
923
|
+
# Wait for active tasks to complete
|
|
924
|
+
pending = [t for t in self._active_tasks if not t.done()]
|
|
925
|
+
|
|
926
|
+
if pending:
|
|
927
|
+
logger.info(
|
|
928
|
+
f"Waiting for {len(pending)} active tasks to complete..."
|
|
929
|
+
f"(Maximum wait time: 30 seconds)"
|
|
930
|
+
)
|
|
931
|
+
|
|
932
|
+
# Set timeout
|
|
933
|
+
try:
|
|
934
|
+
await asyncio.wait_for(
|
|
935
|
+
asyncio.gather(*pending, return_exceptions=True),
|
|
936
|
+
timeout=30.0
|
|
937
|
+
)
|
|
938
|
+
except asyncio.TimeoutError:
|
|
939
|
+
logger.warning("Some tasks timed out, forcing cancellation...")
|
|
940
|
+
|
|
941
|
+
# Force cancel timed out tasks
|
|
942
|
+
for task in pending:
|
|
943
|
+
if not task.done():
|
|
944
|
+
task.cancel()
|
|
945
|
+
|
|
946
|
+
# Wait for cancellation to complete
|
|
947
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
948
|
+
|
|
949
|
+
# Final cleanup
|
|
950
|
+
await self._cleanup_process()
|
|
951
|
+
|
|
952
|
+
# Output final statistics
|
|
953
|
+
final_stats = self.context.get_stats()
|
|
954
|
+
logger.info(
|
|
955
|
+
f"All crawlers gracefully shut down 👋\n"
|
|
956
|
+
f" - Total crawlers: {final_stats['total_crawlers']}\n"
|
|
957
|
+
f" - Successfully completed: {final_stats['completed_crawlers']}\n"
|
|
958
|
+
f" - Failed: {final_stats['failed_crawlers']}\n"
|
|
959
|
+
f" - Success rate: {final_stats['success_rate']:.1f}%\n"
|
|
960
|
+
f" - Total runtime: {final_stats['duration_seconds']} seconds"
|
|
961
|
+
)
|
|
962
|
+
|
|
963
|
+
except Exception as e:
|
|
964
|
+
logger.error(f"Error during shutdown process: {e}", exc_info=True)
|
|
965
|
+
|
|
966
|
+
@classmethod
|
|
967
|
+
def _get_default_settings(cls) -> SettingManager:
|
|
968
|
+
"""
|
|
969
|
+
Load default configuration
|
|
970
|
+
|
|
971
|
+
Provides better error handling and fallback strategy
|
|
972
|
+
"""
|
|
973
|
+
try:
|
|
974
|
+
settings = get_settings()
|
|
975
|
+
_get_logger().debug("Default configuration loaded successfully")
|
|
976
|
+
return settings
|
|
977
|
+
except Exception as e:
|
|
978
|
+
_get_logger().warning(f"Unable to load default configuration: {e}, using empty configuration")
|
|
979
|
+
return SettingManager()
|
|
980
|
+
|
|
981
|
+
def _log_startup_info(self):
|
|
982
|
+
"""Print startup information, including run mode and key configuration checks"""
|
|
983
|
+
# Get run mode
|
|
984
|
+
run_mode = self.settings.get('RUN_MODE', 'standalone')
|
|
985
|
+
|
|
986
|
+
# Get version number
|
|
987
|
+
version = self.settings.get('VERSION', '1.0.0')
|
|
988
|
+
if not version or version == 'None':
|
|
989
|
+
version = '1.0.0'
|
|
990
|
+
|
|
991
|
+
# Build startup info log
|
|
992
|
+
startup_info = [
|
|
993
|
+
f"Crawlo Framework Started v{version}"
|
|
994
|
+
]
|
|
995
|
+
|
|
996
|
+
# Get actual queue type
|
|
997
|
+
queue_type = self.settings.get('QUEUE_TYPE', 'memory')
|
|
998
|
+
|
|
999
|
+
# Display information based on run mode and queue type combination
|
|
1000
|
+
if run_mode == 'distributed':
|
|
1001
|
+
startup_info.append("Run Mode: distributed")
|
|
1002
|
+
startup_info.append("Distributed Mode - Multi-node collaboration supported")
|
|
1003
|
+
# Show Redis configuration
|
|
1004
|
+
redis_host = self.settings.get('REDIS_HOST', 'localhost')
|
|
1005
|
+
redis_port = self.settings.get('REDIS_PORT', 6379)
|
|
1006
|
+
startup_info.append(f"Redis Address: {redis_host}:{redis_port}")
|
|
1007
|
+
elif run_mode == 'standalone':
|
|
1008
|
+
if queue_type == 'redis':
|
|
1009
|
+
startup_info.append("Run Mode: standalone+redis")
|
|
1010
|
+
# Show Redis configuration
|
|
1011
|
+
redis_host = self.settings.get('REDIS_HOST', 'localhost')
|
|
1012
|
+
redis_port = self.settings.get('REDIS_PORT', 6379)
|
|
1013
|
+
startup_info.append(f"Redis Address: {redis_host}:{redis_port}")
|
|
1014
|
+
elif queue_type == 'auto':
|
|
1015
|
+
startup_info.append("Run Mode: standalone+auto")
|
|
1016
|
+
else: # memory
|
|
1017
|
+
startup_info.append("Run Mode: standalone")
|
|
1018
|
+
else:
|
|
1019
|
+
startup_info.append(f"Run Mode: {run_mode}")
|
|
1020
|
+
|
|
1021
|
+
# Print startup information
|
|
1022
|
+
for info in startup_info:
|
|
1023
|
+
logger.info(info)
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
# === Utility functions ===
|
|
1027
|
+
|
|
1028
|
+
def create_crawler_with_optimizations(
|
|
1029
|
+
spider_cls: Type[Spider],
|
|
1030
|
+
settings: Optional[SettingManager] = None,
|
|
1031
|
+
**optimization_kwargs
|
|
1032
|
+
) -> Crawler:
|
|
1033
|
+
"""
|
|
1034
|
+
Create an optimized crawler instance
|
|
1035
|
+
|
|
1036
|
+
:param spider_cls: Spider class
|
|
1037
|
+
:param settings: Settings manager
|
|
1038
|
+
:param optimization_kwargs: Optimization parameters
|
|
1039
|
+
:return: Crawler instance
|
|
1040
|
+
"""
|
|
1041
|
+
if settings is None:
|
|
1042
|
+
settings = SettingManager()
|
|
1043
|
+
|
|
1044
|
+
# Apply optimization configuration
|
|
1045
|
+
for key, value in optimization_kwargs.items():
|
|
1046
|
+
settings.set(key, value)
|
|
1047
|
+
|
|
1048
|
+
context = CrawlerContext()
|
|
1049
|
+
return Crawler(spider_cls, settings, context)
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def create_process_with_large_scale_config(
|
|
1053
|
+
config_type: str = 'balanced',
|
|
1054
|
+
concurrency: int = 16,
|
|
1055
|
+
**kwargs
|
|
1056
|
+
) -> CrawlerProcess:
|
|
1057
|
+
"""
|
|
1058
|
+
Create a process manager that supports large-scale optimization
|
|
1059
|
+
|
|
1060
|
+
:param config_type: Configuration type ('conservative', 'balanced', 'aggressive', 'memory_optimized')
|
|
1061
|
+
:param concurrency: Concurrency count
|
|
1062
|
+
:param kwargs: Other parameters
|
|
1063
|
+
:return: Process manager
|
|
1064
|
+
"""
|
|
1065
|
+
try:
|
|
1066
|
+
from crawlo.utils.large_scale_config import LargeScaleConfig
|
|
1067
|
+
|
|
1068
|
+
# Get optimization configuration
|
|
1069
|
+
config_methods = {
|
|
1070
|
+
'conservative': LargeScaleConfig.conservative_config,
|
|
1071
|
+
'balanced': LargeScaleConfig.balanced_config,
|
|
1072
|
+
'aggressive': LargeScaleConfig.aggressive_config,
|
|
1073
|
+
'memory_optimized': LargeScaleConfig.memory_optimized_config
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
if config_type not in config_methods:
|
|
1077
|
+
logger.warning(f"Unknown configuration type: {config_type}, using default configuration")
|
|
1078
|
+
settings = SettingManager()
|
|
1079
|
+
else:
|
|
1080
|
+
config = config_methods[config_type](concurrency)
|
|
1081
|
+
settings = SettingManager()
|
|
1082
|
+
settings.update(config)
|
|
1083
|
+
|
|
1084
|
+
return CrawlerProcess(
|
|
1085
|
+
settings=settings,
|
|
1086
|
+
max_concurrency=concurrency,
|
|
1087
|
+
**kwargs
|
|
1088
|
+
)
|
|
1089
|
+
|
|
1090
|
+
except ImportError:
|
|
1091
|
+
logger.warning("Large-scale configuration module does not exist, using default configuration")
|
|
1092
|
+
return CrawlerProcess(max_concurrency=concurrency, **kwargs)
|
|
1093
|
+
|
|
1094
|
+
|
|
1095
|
+
# === Exported interfaces ===
|
|
1096
|
+
|
|
1097
|
+
__all__ = [
|
|
1098
|
+
'Crawler',
|
|
1099
|
+
'CrawlerProcess',
|
|
1100
|
+
'CrawlerContext',
|
|
1101
|
+
'create_crawler_with_optimizations',
|
|
1102
|
+
'create_process_with_large_scale_config'
|
|
1103
|
+
]
|