crawlo 1.2.8__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 -47
- 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.8.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.8.dist-info/RECORD +0 -209
- {crawlo-1.2.8.dist-info → crawlo-1.2.9.dist-info}/WHEEL +0 -0
- {crawlo-1.2.8.dist-info → crawlo-1.2.9.dist-info}/entry_points.txt +0 -0
- {crawlo-1.2.8.dist-info → crawlo-1.2.9.dist-info}/top_level.txt +0 -0
crawlo/core/engine.py
CHANGED
|
@@ -1,366 +1,367 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
import asyncio
|
|
4
|
-
import time
|
|
5
|
-
from inspect import iscoroutine
|
|
6
|
-
from typing import Optional, Generator, Callable
|
|
7
|
-
|
|
8
|
-
from crawlo import Request, Item
|
|
9
|
-
from crawlo.spider import Spider
|
|
10
|
-
from crawlo.utils.log import get_logger
|
|
11
|
-
from crawlo.exceptions import OutputError
|
|
12
|
-
from crawlo.core.scheduler import Scheduler
|
|
13
|
-
from crawlo.core.processor import Processor
|
|
14
|
-
from crawlo.task_manager import TaskManager
|
|
15
|
-
from crawlo.project import load_class
|
|
16
|
-
from crawlo.downloader import DownloaderBase
|
|
17
|
-
from crawlo.utils.func_tools import transform
|
|
18
|
-
from crawlo.event import spider_opened, spider_error, request_scheduled
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
class Engine(object):
|
|
22
|
-
|
|
23
|
-
def __init__(self, crawler):
|
|
24
|
-
self.running = False
|
|
25
|
-
self.normal = True
|
|
26
|
-
self.crawler = crawler
|
|
27
|
-
self.settings = crawler.settings
|
|
28
|
-
self.spider: Optional[Spider] = None
|
|
29
|
-
self.downloader: Optional[DownloaderBase] = None
|
|
30
|
-
self.scheduler: Optional[Scheduler] = None
|
|
31
|
-
self.processor: Optional[Processor] = None
|
|
32
|
-
self.start_requests: Optional[Generator] = None
|
|
33
|
-
self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
|
|
34
|
-
|
|
35
|
-
#
|
|
36
|
-
self.max_queue_size = self.settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 200)
|
|
37
|
-
self.generation_batch_size = self.settings.get_int('REQUEST_GENERATION_BATCH_SIZE', 10)
|
|
38
|
-
self.generation_interval = self.settings.get_float('REQUEST_GENERATION_INTERVAL', 0.05)
|
|
39
|
-
self.backpressure_ratio = self.settings.get_float('BACKPRESSURE_RATIO', 0.8) #
|
|
40
|
-
|
|
41
|
-
#
|
|
42
|
-
self._generation_paused = False
|
|
43
|
-
self._last_generation_time = 0
|
|
44
|
-
self._generation_stats = {
|
|
45
|
-
'total_generated': 0,
|
|
46
|
-
'backpressure_events': 0
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
self.logger = get_logger(name=self.__class__.__name__)
|
|
50
|
-
|
|
51
|
-
def _get_downloader_cls(self):
|
|
52
|
-
"""
|
|
53
|
-
# 方式1: 使用 DOWNLOADER_TYPE 简化名称(推荐)
|
|
54
|
-
downloader_type = self.settings.get('DOWNLOADER_TYPE')
|
|
55
|
-
if downloader_type:
|
|
56
|
-
try:
|
|
57
|
-
from crawlo.downloader import get_downloader_class
|
|
58
|
-
downloader_cls = get_downloader_class(downloader_type)
|
|
59
|
-
self.logger.debug(f"
|
|
60
|
-
return downloader_cls
|
|
61
|
-
except (ImportError, ValueError) as e:
|
|
62
|
-
self.logger.warning(f"
|
|
63
|
-
|
|
64
|
-
# 方式2: 使用 DOWNLOADER 完整类路径(兼容旧版本)
|
|
65
|
-
downloader_cls = load_class(self.settings.get('DOWNLOADER'))
|
|
66
|
-
if not issubclass(downloader_cls, DownloaderBase):
|
|
67
|
-
raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
|
|
68
|
-
return downloader_cls
|
|
69
|
-
|
|
70
|
-
def engine_start(self):
|
|
71
|
-
self.running = True
|
|
72
|
-
#
|
|
73
|
-
version = self.settings.get('VERSION', '1.0.0')
|
|
74
|
-
if not version or version == 'None':
|
|
75
|
-
version = '1.0.0'
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
#
|
|
173
|
-
#
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
self.
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
if
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
self.
|
|
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
|
-
self.
|
|
342
|
-
self.
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
self.
|
|
348
|
-
self.
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
await self.
|
|
356
|
-
await self.
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
'
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
import asyncio
|
|
4
|
+
import time
|
|
5
|
+
from inspect import iscoroutine
|
|
6
|
+
from typing import Optional, Generator, Callable
|
|
7
|
+
|
|
8
|
+
from crawlo import Request, Item
|
|
9
|
+
from crawlo.spider import Spider
|
|
10
|
+
from crawlo.utils.log import get_logger
|
|
11
|
+
from crawlo.exceptions import OutputError
|
|
12
|
+
from crawlo.core.scheduler import Scheduler
|
|
13
|
+
from crawlo.core.processor import Processor
|
|
14
|
+
from crawlo.task_manager import TaskManager
|
|
15
|
+
from crawlo.project import load_class
|
|
16
|
+
from crawlo.downloader import DownloaderBase
|
|
17
|
+
from crawlo.utils.func_tools import transform
|
|
18
|
+
from crawlo.event import spider_opened, spider_error, request_scheduled
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Engine(object):
|
|
22
|
+
|
|
23
|
+
def __init__(self, crawler):
|
|
24
|
+
self.running = False
|
|
25
|
+
self.normal = True
|
|
26
|
+
self.crawler = crawler
|
|
27
|
+
self.settings = crawler.settings
|
|
28
|
+
self.spider: Optional[Spider] = None
|
|
29
|
+
self.downloader: Optional[DownloaderBase] = None
|
|
30
|
+
self.scheduler: Optional[Scheduler] = None
|
|
31
|
+
self.processor: Optional[Processor] = None
|
|
32
|
+
self.start_requests: Optional[Generator] = None
|
|
33
|
+
self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
|
|
34
|
+
|
|
35
|
+
# Enhanced control parameters
|
|
36
|
+
self.max_queue_size = self.settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 200)
|
|
37
|
+
self.generation_batch_size = self.settings.get_int('REQUEST_GENERATION_BATCH_SIZE', 10)
|
|
38
|
+
self.generation_interval = self.settings.get_float('REQUEST_GENERATION_INTERVAL', 0.05)
|
|
39
|
+
self.backpressure_ratio = self.settings.get_float('BACKPRESSURE_RATIO', 0.8) # Start backpressure when queue reaches 80%
|
|
40
|
+
|
|
41
|
+
# State tracking
|
|
42
|
+
self._generation_paused = False
|
|
43
|
+
self._last_generation_time = 0
|
|
44
|
+
self._generation_stats = {
|
|
45
|
+
'total_generated': 0,
|
|
46
|
+
'backpressure_events': 0
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
self.logger = get_logger(name=self.__class__.__name__)
|
|
50
|
+
|
|
51
|
+
def _get_downloader_cls(self):
|
|
52
|
+
"""Get downloader class, supports multiple configuration methods"""
|
|
53
|
+
# 方式1: 使用 DOWNLOADER_TYPE 简化名称(推荐)
|
|
54
|
+
downloader_type = self.settings.get('DOWNLOADER_TYPE')
|
|
55
|
+
if downloader_type:
|
|
56
|
+
try:
|
|
57
|
+
from crawlo.downloader import get_downloader_class
|
|
58
|
+
downloader_cls = get_downloader_class(downloader_type)
|
|
59
|
+
self.logger.debug(f"Using downloader type: {downloader_type} -> {downloader_cls.__name__}")
|
|
60
|
+
return downloader_cls
|
|
61
|
+
except (ImportError, ValueError) as e:
|
|
62
|
+
self.logger.warning(f"Unable to use downloader type '{downloader_type}': {e}, falling back to default configuration")
|
|
63
|
+
|
|
64
|
+
# 方式2: 使用 DOWNLOADER 完整类路径(兼容旧版本)
|
|
65
|
+
downloader_cls = load_class(self.settings.get('DOWNLOADER'))
|
|
66
|
+
if not issubclass(downloader_cls, DownloaderBase):
|
|
67
|
+
raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
|
|
68
|
+
return downloader_cls
|
|
69
|
+
|
|
70
|
+
def engine_start(self):
|
|
71
|
+
self.running = True
|
|
72
|
+
# Get version number, use default value if failed to get
|
|
73
|
+
version = self.settings.get('VERSION', '1.0.0')
|
|
74
|
+
if not version or version == 'None':
|
|
75
|
+
version = '1.0.0'
|
|
76
|
+
# Change INFO level log to DEBUG level to avoid duplication with CrawlerProcess startup log
|
|
77
|
+
self.logger.debug(
|
|
78
|
+
f"Crawlo Started version {version} . "
|
|
79
|
+
# f"(project name : {self.settings.get('PROJECT_NAME')})"
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
async def start_spider(self, spider):
|
|
83
|
+
self.spider = spider
|
|
84
|
+
|
|
85
|
+
self.scheduler = Scheduler.create_instance(self.crawler)
|
|
86
|
+
if hasattr(self.scheduler, 'open'):
|
|
87
|
+
if asyncio.iscoroutinefunction(self.scheduler.open):
|
|
88
|
+
await self.scheduler.open()
|
|
89
|
+
else:
|
|
90
|
+
self.scheduler.open()
|
|
91
|
+
|
|
92
|
+
downloader_cls = self._get_downloader_cls()
|
|
93
|
+
self.downloader = downloader_cls(self.crawler)
|
|
94
|
+
if hasattr(self.downloader, 'open'):
|
|
95
|
+
if asyncio.iscoroutinefunction(self.downloader.open):
|
|
96
|
+
self.downloader.open()
|
|
97
|
+
else:
|
|
98
|
+
# DownloaderBase.open() 是同步方法,直接调用而不是await
|
|
99
|
+
self.downloader.open()
|
|
100
|
+
|
|
101
|
+
self.processor = Processor(self.crawler)
|
|
102
|
+
if hasattr(self.processor, 'open'):
|
|
103
|
+
if asyncio.iscoroutinefunction(self.processor.open):
|
|
104
|
+
await self.processor.open()
|
|
105
|
+
else:
|
|
106
|
+
# Processor.open() 是同步方法
|
|
107
|
+
self.processor.open()
|
|
108
|
+
|
|
109
|
+
# 在处理器初始化之后初始化扩展管理器,确保日志输出顺序正确
|
|
110
|
+
# 中间件 -> 管道 -> 扩展
|
|
111
|
+
if not hasattr(self.crawler, 'extension') or not self.crawler.extension:
|
|
112
|
+
self.crawler.extension = self.crawler._create_extension()
|
|
113
|
+
|
|
114
|
+
self.start_requests = iter(spider.start_requests())
|
|
115
|
+
await self._open_spider()
|
|
116
|
+
|
|
117
|
+
async def crawl(self):
|
|
118
|
+
"""
|
|
119
|
+
Crawl the spider
|
|
120
|
+
Enhanced version supports intelligent request generation and backpressure control
|
|
121
|
+
"""
|
|
122
|
+
generation_task = None
|
|
123
|
+
|
|
124
|
+
try:
|
|
125
|
+
# 启动请求生成任务(如果启用了受控生成)
|
|
126
|
+
if (self.start_requests and
|
|
127
|
+
self.settings.get_bool('ENABLE_CONTROLLED_REQUEST_GENERATION', False)):
|
|
128
|
+
generation_task = asyncio.create_task(
|
|
129
|
+
self._controlled_request_generation()
|
|
130
|
+
)
|
|
131
|
+
else:
|
|
132
|
+
# 传统方式处理启动请求
|
|
133
|
+
generation_task = asyncio.create_task(
|
|
134
|
+
self._traditional_request_generation()
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# 主爬取循环
|
|
138
|
+
while self.running:
|
|
139
|
+
# 获取并处理请求
|
|
140
|
+
if request := await self._get_next_request():
|
|
141
|
+
await self._crawl(request)
|
|
142
|
+
|
|
143
|
+
# 检查退出条件
|
|
144
|
+
if await self._should_exit():
|
|
145
|
+
break
|
|
146
|
+
|
|
147
|
+
# 短暂休息避免忙等
|
|
148
|
+
await asyncio.sleep(0.001)
|
|
149
|
+
|
|
150
|
+
finally:
|
|
151
|
+
# 清理生成任务
|
|
152
|
+
if generation_task and not generation_task.done():
|
|
153
|
+
generation_task.cancel()
|
|
154
|
+
try:
|
|
155
|
+
await generation_task
|
|
156
|
+
except asyncio.CancelledError:
|
|
157
|
+
pass
|
|
158
|
+
|
|
159
|
+
await self.close_spider()
|
|
160
|
+
|
|
161
|
+
async def _traditional_request_generation(self):
|
|
162
|
+
"""Traditional request generation method (compatible with older versions)"""
|
|
163
|
+
while self.running:
|
|
164
|
+
try:
|
|
165
|
+
start_request = next(self.start_requests)
|
|
166
|
+
# 请求入队
|
|
167
|
+
await self.enqueue_request(start_request)
|
|
168
|
+
except StopIteration:
|
|
169
|
+
self.start_requests = None
|
|
170
|
+
break
|
|
171
|
+
except Exception as exp:
|
|
172
|
+
# 1. All requests have been processed
|
|
173
|
+
# 2. Is scheduler idle
|
|
174
|
+
# 3. Is downloader idle
|
|
175
|
+
if not await self._exit():
|
|
176
|
+
continue
|
|
177
|
+
self.running = False
|
|
178
|
+
if self.start_requests is not None:
|
|
179
|
+
self.logger.error(f"Error occurred while starting request: {str(exp)}")
|
|
180
|
+
await asyncio.sleep(0.001)
|
|
181
|
+
|
|
182
|
+
async def _controlled_request_generation(self):
|
|
183
|
+
"""Controlled request generation (enhanced features)"""
|
|
184
|
+
self.logger.info("Starting controlled request generation")
|
|
185
|
+
|
|
186
|
+
batch = []
|
|
187
|
+
total_generated = 0
|
|
188
|
+
|
|
189
|
+
try:
|
|
190
|
+
for request in self.start_requests:
|
|
191
|
+
batch.append(request)
|
|
192
|
+
|
|
193
|
+
# 批量处理
|
|
194
|
+
if len(batch) >= self.generation_batch_size:
|
|
195
|
+
generated = await self._process_generation_batch(batch)
|
|
196
|
+
total_generated += generated
|
|
197
|
+
batch = []
|
|
198
|
+
|
|
199
|
+
# 背压检查
|
|
200
|
+
if await self._should_pause_generation():
|
|
201
|
+
await self._wait_for_capacity()
|
|
202
|
+
|
|
203
|
+
# 处理剩余请求
|
|
204
|
+
if batch:
|
|
205
|
+
generated = await self._process_generation_batch(batch)
|
|
206
|
+
total_generated += generated
|
|
207
|
+
|
|
208
|
+
except Exception as e:
|
|
209
|
+
self.logger.error(f"Request generation failed: {e}")
|
|
210
|
+
|
|
211
|
+
finally:
|
|
212
|
+
self.start_requests = None
|
|
213
|
+
self.logger.info(f"Request generation completed, total: {total_generated}")
|
|
214
|
+
|
|
215
|
+
async def _process_generation_batch(self, batch) -> int:
|
|
216
|
+
"""Process a batch of requests"""
|
|
217
|
+
generated = 0
|
|
218
|
+
|
|
219
|
+
for request in batch:
|
|
220
|
+
if not self.running:
|
|
221
|
+
break
|
|
222
|
+
|
|
223
|
+
# 等待队列有空间
|
|
224
|
+
while await self._is_queue_full() and self.running:
|
|
225
|
+
await asyncio.sleep(0.1)
|
|
226
|
+
|
|
227
|
+
if self.running:
|
|
228
|
+
await self.enqueue_request(request)
|
|
229
|
+
generated += 1
|
|
230
|
+
self._generation_stats['total_generated'] += 1
|
|
231
|
+
|
|
232
|
+
# 控制生成速度
|
|
233
|
+
if self.generation_interval > 0:
|
|
234
|
+
await asyncio.sleep(self.generation_interval)
|
|
235
|
+
|
|
236
|
+
return generated
|
|
237
|
+
|
|
238
|
+
async def _should_pause_generation(self) -> bool:
|
|
239
|
+
"""Determine whether generation should be paused"""
|
|
240
|
+
# 检查队列大小
|
|
241
|
+
if await self._is_queue_full():
|
|
242
|
+
return True
|
|
243
|
+
|
|
244
|
+
# 检查任务管理器负载
|
|
245
|
+
if self.task_manager:
|
|
246
|
+
current_tasks = len(self.task_manager.current_task)
|
|
247
|
+
if hasattr(self.task_manager, 'semaphore'):
|
|
248
|
+
max_concurrency = getattr(self.task_manager.semaphore, '_initial_value', 8)
|
|
249
|
+
if current_tasks >= max_concurrency * self.backpressure_ratio:
|
|
250
|
+
return True
|
|
251
|
+
|
|
252
|
+
return False
|
|
253
|
+
|
|
254
|
+
async def _is_queue_full(self) -> bool:
|
|
255
|
+
"""Check if queue is full"""
|
|
256
|
+
if not self.scheduler:
|
|
257
|
+
return False
|
|
258
|
+
|
|
259
|
+
queue_size = len(self.scheduler)
|
|
260
|
+
return queue_size >= self.max_queue_size * self.backpressure_ratio
|
|
261
|
+
|
|
262
|
+
async def _wait_for_capacity(self):
|
|
263
|
+
"""Wait for system to have sufficient capacity"""
|
|
264
|
+
self._generation_stats['backpressure_events'] += 1
|
|
265
|
+
self.logger.debug("Backpressure triggered, pausing request generation")
|
|
266
|
+
|
|
267
|
+
wait_time = 0.1
|
|
268
|
+
max_wait = 2.0
|
|
269
|
+
|
|
270
|
+
while await self._should_pause_generation() and self.running:
|
|
271
|
+
await asyncio.sleep(wait_time)
|
|
272
|
+
wait_time = min(wait_time * 1.1, max_wait)
|
|
273
|
+
|
|
274
|
+
async def _open_spider(self):
|
|
275
|
+
asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
|
|
276
|
+
crawling = asyncio.create_task(self.crawl())
|
|
277
|
+
await crawling
|
|
278
|
+
|
|
279
|
+
async def _crawl(self, request):
|
|
280
|
+
# TODO 实现并发
|
|
281
|
+
async def crawl_task():
|
|
282
|
+
outputs = await self._fetch(request)
|
|
283
|
+
# TODO 处理output
|
|
284
|
+
if outputs:
|
|
285
|
+
await self._handle_spider_output(outputs)
|
|
286
|
+
|
|
287
|
+
# 使用异步任务创建,遵守并发限制
|
|
288
|
+
await self.task_manager.create_task(crawl_task())
|
|
289
|
+
|
|
290
|
+
async def _fetch(self, request):
|
|
291
|
+
async def _successful(_response):
|
|
292
|
+
callback: Callable = request.callback or self.spider.parse
|
|
293
|
+
if _outputs := callback(_response):
|
|
294
|
+
if iscoroutine(_outputs):
|
|
295
|
+
await _outputs
|
|
296
|
+
else:
|
|
297
|
+
return transform(_outputs, _response)
|
|
298
|
+
|
|
299
|
+
_response = await self.downloader.fetch(request)
|
|
300
|
+
if _response is None:
|
|
301
|
+
return None
|
|
302
|
+
output = await _successful(_response)
|
|
303
|
+
return output
|
|
304
|
+
|
|
305
|
+
async def enqueue_request(self, start_request):
|
|
306
|
+
await self._schedule_request(start_request)
|
|
307
|
+
|
|
308
|
+
async def _schedule_request(self, request):
|
|
309
|
+
# TODO 去重
|
|
310
|
+
if await self.scheduler.enqueue_request(request):
|
|
311
|
+
asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
|
|
312
|
+
|
|
313
|
+
async def _get_next_request(self):
|
|
314
|
+
return await self.scheduler.next_request()
|
|
315
|
+
|
|
316
|
+
async def _handle_spider_output(self, outputs):
|
|
317
|
+
async for spider_output in outputs:
|
|
318
|
+
if isinstance(spider_output, (Request, Item)):
|
|
319
|
+
await self.processor.enqueue(spider_output)
|
|
320
|
+
elif isinstance(spider_output, Exception):
|
|
321
|
+
asyncio.create_task(
|
|
322
|
+
self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
|
|
323
|
+
)
|
|
324
|
+
raise spider_output
|
|
325
|
+
else:
|
|
326
|
+
raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
|
|
327
|
+
|
|
328
|
+
async def _exit(self):
|
|
329
|
+
if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
|
|
330
|
+
return True
|
|
331
|
+
return False
|
|
332
|
+
|
|
333
|
+
async def _should_exit(self) -> bool:
|
|
334
|
+
"""检查是否应该退出"""
|
|
335
|
+
# 没有启动请求,且所有队列都空闲
|
|
336
|
+
if self.start_requests is None:
|
|
337
|
+
# 使用异步的idle检查方法以获得更精确的结果
|
|
338
|
+
scheduler_idle = await self.scheduler.async_idle() if hasattr(self.scheduler, 'async_idle') else self.scheduler.idle()
|
|
339
|
+
|
|
340
|
+
if (scheduler_idle and
|
|
341
|
+
self.downloader.idle() and
|
|
342
|
+
self.task_manager.all_done() and
|
|
343
|
+
self.processor.idle()):
|
|
344
|
+
# 增加额外检查确保所有任务都完成
|
|
345
|
+
await asyncio.sleep(0.1) # 短暂等待确保没有新的任务加入
|
|
346
|
+
if (await self.scheduler.async_idle() and
|
|
347
|
+
self.downloader.idle() and
|
|
348
|
+
self.task_manager.all_done() and
|
|
349
|
+
self.processor.idle()):
|
|
350
|
+
return True
|
|
351
|
+
|
|
352
|
+
return False
|
|
353
|
+
|
|
354
|
+
async def close_spider(self):
|
|
355
|
+
await asyncio.gather(*self.task_manager.current_task)
|
|
356
|
+
await self.scheduler.close()
|
|
357
|
+
await self.downloader.close()
|
|
358
|
+
if self.normal:
|
|
359
|
+
await self.crawler.close()
|
|
360
|
+
|
|
361
|
+
def get_generation_stats(self) -> dict:
|
|
362
|
+
"""获取生成统计"""
|
|
363
|
+
return {
|
|
364
|
+
**self._generation_stats,
|
|
365
|
+
'queue_size': len(self.scheduler) if self.scheduler else 0,
|
|
366
|
+
'active_tasks': len(self.task_manager.current_task) if self.task_manager else 0
|
|
366
367
|
}
|