crawlo 1.1.8__py3-none-any.whl → 1.2.0__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 +61 -61
- crawlo/__version__.py +1 -1
- crawlo/cleaners/__init__.py +60 -60
- crawlo/cleaners/data_formatter.py +225 -225
- crawlo/cleaners/encoding_converter.py +125 -125
- crawlo/cleaners/text_cleaner.py +232 -232
- crawlo/cli.py +65 -65
- crawlo/commands/__init__.py +14 -14
- crawlo/commands/check.py +594 -594
- crawlo/commands/genspider.py +151 -151
- crawlo/commands/help.py +132 -132
- crawlo/commands/list.py +155 -155
- crawlo/commands/run.py +292 -292
- crawlo/commands/startproject.py +418 -418
- crawlo/commands/stats.py +188 -188
- crawlo/commands/utils.py +186 -186
- crawlo/config.py +312 -312
- crawlo/config_validator.py +252 -252
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +354 -345
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +143 -136
- crawlo/crawler.py +1027 -1027
- crawlo/downloader/__init__.py +266 -266
- crawlo/downloader/aiohttp_downloader.py +220 -220
- crawlo/downloader/cffi_downloader.py +256 -256
- crawlo/downloader/httpx_downloader.py +259 -259
- crawlo/downloader/hybrid_downloader.py +213 -213
- 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 +37 -37
- 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 +280 -280
- crawlo/filters/memory_filter.py +269 -269
- crawlo/items/__init__.py +23 -23
- crawlo/items/base.py +21 -21
- crawlo/items/fields.py +53 -53
- crawlo/items/items.py +104 -104
- crawlo/middleware/__init__.py +21 -21
- crawlo/middleware/default_header.py +32 -32
- crawlo/middleware/download_delay.py +28 -28
- crawlo/middleware/middleware_manager.py +135 -135
- crawlo/middleware/proxy.py +272 -272
- crawlo/middleware/request_ignore.py +30 -30
- crawlo/middleware/response_code.py +18 -18
- crawlo/middleware/response_filter.py +26 -26
- crawlo/middleware/retry.py +124 -124
- crawlo/mode_manager.py +211 -211
- crawlo/network/__init__.py +21 -21
- crawlo/network/request.py +338 -338
- crawlo/network/response.py +359 -359
- crawlo/pipelines/__init__.py +21 -21
- crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +316 -316
- crawlo/pipelines/database_dedup_pipeline.py +224 -224
- 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 +316 -316
- crawlo/pipelines/pipeline_manager.py +61 -61
- crawlo/pipelines/redis_dedup_pipeline.py +167 -167
- crawlo/project.py +187 -187
- crawlo/queue/pqueue.py +37 -37
- crawlo/queue/queue_manager.py +337 -334
- crawlo/queue/redis_priority_queue.py +298 -298
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +219 -219
- crawlo/settings/setting_manager.py +122 -122
- crawlo/spider/__init__.py +639 -639
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +130 -130
- 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 +109 -109
- crawlo/templates/project/pipelines.py.tmpl +96 -96
- crawlo/templates/project/run.py.tmpl +45 -45
- crawlo/templates/project/settings.py.tmpl +326 -326
- crawlo/templates/project/settings_distributed.py.tmpl +119 -119
- crawlo/templates/project/settings_gentle.py.tmpl +94 -94
- crawlo/templates/project/settings_high_performance.py.tmpl +151 -151
- crawlo/templates/project/settings_simple.py.tmpl +68 -68
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/spider/spider.py.tmpl +141 -141
- crawlo/tools/__init__.py +182 -182
- crawlo/tools/anti_crawler.py +268 -268
- crawlo/tools/authenticated_proxy.py +240 -240
- crawlo/tools/data_validator.py +180 -180
- crawlo/tools/date_tools.py +35 -35
- crawlo/tools/distributed_coordinator.py +386 -386
- crawlo/tools/retry_mechanism.py +220 -220
- crawlo/tools/scenario_adapter.py +262 -262
- crawlo/utils/__init__.py +35 -35
- crawlo/utils/batch_processor.py +260 -260
- crawlo/utils/controlled_spider_mixin.py +439 -439
- crawlo/utils/date_tools.py +290 -290
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/enhanced_error_handler.py +359 -359
- crawlo/utils/env_config.py +105 -105
- crawlo/utils/error_handler.py +125 -125
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +286 -286
- crawlo/utils/large_scale_helper.py +343 -343
- crawlo/utils/log.py +128 -128
- crawlo/utils/performance_monitor.py +284 -284
- crawlo/utils/queue_helper.py +175 -175
- crawlo/utils/redis_connection_pool.py +334 -334
- crawlo/utils/redis_key_validator.py +199 -199
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +219 -219
- crawlo/utils/spider_loader.py +62 -62
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +4 -4
- crawlo/utils/url.py +39 -39
- crawlo-1.2.0.dist-info/METADATA +697 -0
- crawlo-1.2.0.dist-info/RECORD +190 -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 +236 -236
- tests/cleaners_example.py +160 -160
- tests/config_validation_demo.py +102 -102
- tests/controlled_spider_example.py +205 -205
- tests/date_tools_example.py +180 -180
- 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/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_validator.py +193 -193
- tests/test_date_tools.py +123 -123
- tests/test_double_crawlo_fix.py +207 -207
- tests/test_double_crawlo_fix_simple.py +124 -124
- 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 +356 -356
- tests/test_item_dedup_redis_key.py +122 -122
- tests/test_parsel.py +29 -29
- tests/test_performance.py +327 -327
- tests/test_proxy_health_check.py +32 -32
- tests/test_proxy_middleware_integration.py +136 -136
- 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 +174 -231
- tests/test_queue_manager_redis_key.py +176 -176
- 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_serialization.py +70 -70
- tests/test_response_improvements.py +152 -152
- tests/test_scheduler.py +241 -241
- 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 +153 -153
- tests/tools_example.py +257 -257
- crawlo-1.1.8.dist-info/METADATA +0 -626
- crawlo-1.1.8.dist-info/RECORD +0 -190
- {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/WHEEL +0 -0
- {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.8.dist-info → crawlo-1.2.0.dist-info}/top_level.txt +0 -0
crawlo/core/engine.py
CHANGED
|
@@ -1,346 +1,355 @@
|
|
|
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) # 队列达到80%时启动背压
|
|
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"使用下载器类型: {downloader_type} -> {downloader_cls.__name__}")
|
|
60
|
-
return downloader_cls
|
|
61
|
-
except (ImportError, ValueError) as e:
|
|
62
|
-
self.logger.warning(f"无法使用下载器类型 '{downloader_type}': {e},回退到默认配置")
|
|
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
|
-
self.logger.info(
|
|
73
|
-
f"Crawlo (version {self.settings.get('VERSION')}) started. "
|
|
74
|
-
f"(project name : {self.settings.get('PROJECT_NAME')})"
|
|
75
|
-
)
|
|
76
|
-
|
|
77
|
-
async def start_spider(self, spider):
|
|
78
|
-
self.spider = spider
|
|
79
|
-
|
|
80
|
-
self.scheduler = Scheduler.create_instance(self.crawler)
|
|
81
|
-
if hasattr(self.scheduler, 'open'):
|
|
82
|
-
if asyncio.iscoroutinefunction(self.scheduler.open):
|
|
83
|
-
await self.scheduler.open()
|
|
84
|
-
else:
|
|
85
|
-
self.scheduler.open()
|
|
86
|
-
|
|
87
|
-
downloader_cls = self._get_downloader_cls()
|
|
88
|
-
self.downloader = downloader_cls(self.crawler)
|
|
89
|
-
if hasattr(self.downloader, 'open'):
|
|
90
|
-
if asyncio.iscoroutinefunction(self.downloader.open):
|
|
91
|
-
await self.downloader.open()
|
|
92
|
-
else:
|
|
93
|
-
self.downloader.open()
|
|
94
|
-
|
|
95
|
-
self.processor = Processor(self.crawler)
|
|
96
|
-
if hasattr(self.processor, 'open'):
|
|
97
|
-
if asyncio.iscoroutinefunction(self.processor.open):
|
|
98
|
-
await self.processor.open()
|
|
99
|
-
else:
|
|
100
|
-
self.processor.open()
|
|
101
|
-
|
|
102
|
-
self.start_requests = iter(spider.start_requests())
|
|
103
|
-
await self._open_spider()
|
|
104
|
-
|
|
105
|
-
async def crawl(self):
|
|
106
|
-
"""
|
|
107
|
-
Crawl the spider
|
|
108
|
-
增强版本支持智能请求生成和背压控制
|
|
109
|
-
"""
|
|
110
|
-
generation_task = None
|
|
111
|
-
|
|
112
|
-
try:
|
|
113
|
-
# 启动请求生成任务(如果启用了受控生成)
|
|
114
|
-
if (self.start_requests and
|
|
115
|
-
self.settings.get_bool('ENABLE_CONTROLLED_REQUEST_GENERATION', False)):
|
|
116
|
-
generation_task = asyncio.create_task(
|
|
117
|
-
self._controlled_request_generation()
|
|
118
|
-
)
|
|
119
|
-
else:
|
|
120
|
-
# 传统方式处理启动请求
|
|
121
|
-
generation_task = asyncio.create_task(
|
|
122
|
-
self._traditional_request_generation()
|
|
123
|
-
)
|
|
124
|
-
|
|
125
|
-
# 主爬取循环
|
|
126
|
-
while self.running:
|
|
127
|
-
# 获取并处理请求
|
|
128
|
-
if request := await self._get_next_request():
|
|
129
|
-
await self._crawl(request)
|
|
130
|
-
|
|
131
|
-
# 检查退出条件
|
|
132
|
-
if await self._should_exit():
|
|
133
|
-
break
|
|
134
|
-
|
|
135
|
-
# 短暂休息避免忙等
|
|
136
|
-
await asyncio.sleep(0.001)
|
|
137
|
-
|
|
138
|
-
finally:
|
|
139
|
-
# 清理生成任务
|
|
140
|
-
if generation_task and not generation_task.done():
|
|
141
|
-
generation_task.cancel()
|
|
142
|
-
try:
|
|
143
|
-
await generation_task
|
|
144
|
-
except asyncio.CancelledError:
|
|
145
|
-
pass
|
|
146
|
-
|
|
147
|
-
await self.close_spider()
|
|
148
|
-
|
|
149
|
-
async def _traditional_request_generation(self):
|
|
150
|
-
"""传统的请求生成方式(兼容旧版本)"""
|
|
151
|
-
while self.running:
|
|
152
|
-
try:
|
|
153
|
-
start_request = next(self.start_requests)
|
|
154
|
-
# 请求入队
|
|
155
|
-
await self.enqueue_request(start_request)
|
|
156
|
-
except StopIteration:
|
|
157
|
-
self.start_requests = None
|
|
158
|
-
break
|
|
159
|
-
except Exception as exp:
|
|
160
|
-
# 1、发去请求的request全部运行完毕
|
|
161
|
-
# 2、调度器是否空闲
|
|
162
|
-
# 3、下载器是否空闲
|
|
163
|
-
if not await self._exit():
|
|
164
|
-
continue
|
|
165
|
-
self.running = False
|
|
166
|
-
if self.start_requests is not None:
|
|
167
|
-
self.logger.error(f"启动请求时发生错误: {str(exp)}")
|
|
168
|
-
await asyncio.sleep(0.001)
|
|
169
|
-
|
|
170
|
-
async def _controlled_request_generation(self):
|
|
171
|
-
"""受控的请求生成(增强功能)"""
|
|
172
|
-
self.logger.info("🎛️ 启动受控请求生成")
|
|
173
|
-
|
|
174
|
-
batch = []
|
|
175
|
-
total_generated = 0
|
|
176
|
-
|
|
177
|
-
try:
|
|
178
|
-
for request in self.start_requests:
|
|
179
|
-
batch.append(request)
|
|
180
|
-
|
|
181
|
-
# 批量处理
|
|
182
|
-
if len(batch) >= self.generation_batch_size:
|
|
183
|
-
generated = await self._process_generation_batch(batch)
|
|
184
|
-
total_generated += generated
|
|
185
|
-
batch = []
|
|
186
|
-
|
|
187
|
-
# 背压检查
|
|
188
|
-
if await self._should_pause_generation():
|
|
189
|
-
await self._wait_for_capacity()
|
|
190
|
-
|
|
191
|
-
# 处理剩余请求
|
|
192
|
-
if batch:
|
|
193
|
-
generated = await self._process_generation_batch(batch)
|
|
194
|
-
total_generated += generated
|
|
195
|
-
|
|
196
|
-
except Exception as e:
|
|
197
|
-
self.logger.error(f"❌ 请求生成失败: {e}")
|
|
198
|
-
|
|
199
|
-
finally:
|
|
200
|
-
self.start_requests = None
|
|
201
|
-
self.logger.info(f"🎉 请求生成完成,总计: {total_generated}")
|
|
202
|
-
|
|
203
|
-
async def _process_generation_batch(self, batch) -> int:
|
|
204
|
-
"""处理一批请求"""
|
|
205
|
-
generated = 0
|
|
206
|
-
|
|
207
|
-
for request in batch:
|
|
208
|
-
if not self.running:
|
|
209
|
-
break
|
|
210
|
-
|
|
211
|
-
# 等待队列有空间
|
|
212
|
-
while await self._is_queue_full() and self.running:
|
|
213
|
-
await asyncio.sleep(0.1)
|
|
214
|
-
|
|
215
|
-
if self.running:
|
|
216
|
-
await self.enqueue_request(request)
|
|
217
|
-
generated += 1
|
|
218
|
-
self._generation_stats['total_generated'] += 1
|
|
219
|
-
|
|
220
|
-
# 控制生成速度
|
|
221
|
-
if self.generation_interval > 0:
|
|
222
|
-
await asyncio.sleep(self.generation_interval)
|
|
223
|
-
|
|
224
|
-
return generated
|
|
225
|
-
|
|
226
|
-
async def _should_pause_generation(self) -> bool:
|
|
227
|
-
"""判断是否应该暂停生成"""
|
|
228
|
-
# 检查队列大小
|
|
229
|
-
if await self._is_queue_full():
|
|
230
|
-
return True
|
|
231
|
-
|
|
232
|
-
# 检查任务管理器负载
|
|
233
|
-
if self.task_manager:
|
|
234
|
-
current_tasks = len(self.task_manager.current_task)
|
|
235
|
-
if hasattr(self.task_manager, 'semaphore'):
|
|
236
|
-
max_concurrency = getattr(self.task_manager.semaphore, '_initial_value', 8)
|
|
237
|
-
if current_tasks >= max_concurrency * self.backpressure_ratio:
|
|
238
|
-
return True
|
|
239
|
-
|
|
240
|
-
return False
|
|
241
|
-
|
|
242
|
-
async def _is_queue_full(self) -> bool:
|
|
243
|
-
"""检查队列是否已满"""
|
|
244
|
-
if not self.scheduler:
|
|
245
|
-
return False
|
|
246
|
-
|
|
247
|
-
queue_size = len(self.scheduler)
|
|
248
|
-
return queue_size >= self.max_queue_size * self.backpressure_ratio
|
|
249
|
-
|
|
250
|
-
async def _wait_for_capacity(self):
|
|
251
|
-
"""等待系统有足够容量"""
|
|
252
|
-
self._generation_stats['backpressure_events'] += 1
|
|
253
|
-
self.logger.debug("⏸️ 触发背压,暂停请求生成")
|
|
254
|
-
|
|
255
|
-
wait_time = 0.1
|
|
256
|
-
max_wait = 2.0
|
|
257
|
-
|
|
258
|
-
while await self._should_pause_generation() and self.running:
|
|
259
|
-
await asyncio.sleep(wait_time)
|
|
260
|
-
wait_time = min(wait_time * 1.1, max_wait)
|
|
261
|
-
|
|
262
|
-
async def _open_spider(self):
|
|
263
|
-
asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
|
|
264
|
-
crawling = asyncio.create_task(self.crawl())
|
|
265
|
-
await crawling
|
|
266
|
-
|
|
267
|
-
async def _crawl(self, request):
|
|
268
|
-
# TODO 实现并发
|
|
269
|
-
async def crawl_task():
|
|
270
|
-
outputs = await self._fetch(request)
|
|
271
|
-
# TODO 处理output
|
|
272
|
-
if outputs:
|
|
273
|
-
await self._handle_spider_output(outputs)
|
|
274
|
-
|
|
275
|
-
# 使用异步任务创建,遵守并发限制
|
|
276
|
-
await self.task_manager.create_task(crawl_task())
|
|
277
|
-
|
|
278
|
-
async def _fetch(self, request):
|
|
279
|
-
async def _successful(_response):
|
|
280
|
-
callback: Callable = request.callback or self.spider.parse
|
|
281
|
-
if _outputs := callback(_response):
|
|
282
|
-
if iscoroutine(_outputs):
|
|
283
|
-
await _outputs
|
|
284
|
-
else:
|
|
285
|
-
return transform(_outputs, _response)
|
|
286
|
-
|
|
287
|
-
_response = await self.downloader.fetch(request)
|
|
288
|
-
if _response is None:
|
|
289
|
-
return None
|
|
290
|
-
output = await _successful(_response)
|
|
291
|
-
return output
|
|
292
|
-
|
|
293
|
-
async def enqueue_request(self, start_request):
|
|
294
|
-
await self._schedule_request(start_request)
|
|
295
|
-
|
|
296
|
-
async def _schedule_request(self, request):
|
|
297
|
-
# TODO 去重
|
|
298
|
-
if await self.scheduler.enqueue_request(request):
|
|
299
|
-
asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
|
|
300
|
-
|
|
301
|
-
async def _get_next_request(self):
|
|
302
|
-
return await self.scheduler.next_request()
|
|
303
|
-
|
|
304
|
-
async def _handle_spider_output(self, outputs):
|
|
305
|
-
async for spider_output in outputs:
|
|
306
|
-
if isinstance(spider_output, (Request, Item)):
|
|
307
|
-
await self.processor.enqueue(spider_output)
|
|
308
|
-
elif isinstance(spider_output, Exception):
|
|
309
|
-
asyncio.create_task(
|
|
310
|
-
self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
|
|
311
|
-
)
|
|
312
|
-
raise spider_output
|
|
313
|
-
else:
|
|
314
|
-
raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
|
|
315
|
-
|
|
316
|
-
async def _exit(self):
|
|
317
|
-
if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
|
|
318
|
-
return True
|
|
319
|
-
return False
|
|
320
|
-
|
|
321
|
-
async def _should_exit(self) -> bool:
|
|
322
|
-
"""检查是否应该退出(增强版本)"""
|
|
323
|
-
# 没有启动请求,且所有队列都空闲
|
|
324
|
-
if
|
|
325
|
-
|
|
326
|
-
self.
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
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) # 队列达到80%时启动背压
|
|
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"使用下载器类型: {downloader_type} -> {downloader_cls.__name__}")
|
|
60
|
+
return downloader_cls
|
|
61
|
+
except (ImportError, ValueError) as e:
|
|
62
|
+
self.logger.warning(f"无法使用下载器类型 '{downloader_type}': {e},回退到默认配置")
|
|
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
|
+
self.logger.info(
|
|
73
|
+
f"Crawlo (version {self.settings.get('VERSION')}) started. "
|
|
74
|
+
f"(project name : {self.settings.get('PROJECT_NAME')})"
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
async def start_spider(self, spider):
|
|
78
|
+
self.spider = spider
|
|
79
|
+
|
|
80
|
+
self.scheduler = Scheduler.create_instance(self.crawler)
|
|
81
|
+
if hasattr(self.scheduler, 'open'):
|
|
82
|
+
if asyncio.iscoroutinefunction(self.scheduler.open):
|
|
83
|
+
await self.scheduler.open()
|
|
84
|
+
else:
|
|
85
|
+
self.scheduler.open()
|
|
86
|
+
|
|
87
|
+
downloader_cls = self._get_downloader_cls()
|
|
88
|
+
self.downloader = downloader_cls(self.crawler)
|
|
89
|
+
if hasattr(self.downloader, 'open'):
|
|
90
|
+
if asyncio.iscoroutinefunction(self.downloader.open):
|
|
91
|
+
await self.downloader.open()
|
|
92
|
+
else:
|
|
93
|
+
self.downloader.open()
|
|
94
|
+
|
|
95
|
+
self.processor = Processor(self.crawler)
|
|
96
|
+
if hasattr(self.processor, 'open'):
|
|
97
|
+
if asyncio.iscoroutinefunction(self.processor.open):
|
|
98
|
+
await self.processor.open()
|
|
99
|
+
else:
|
|
100
|
+
self.processor.open()
|
|
101
|
+
|
|
102
|
+
self.start_requests = iter(spider.start_requests())
|
|
103
|
+
await self._open_spider()
|
|
104
|
+
|
|
105
|
+
async def crawl(self):
|
|
106
|
+
"""
|
|
107
|
+
Crawl the spider
|
|
108
|
+
增强版本支持智能请求生成和背压控制
|
|
109
|
+
"""
|
|
110
|
+
generation_task = None
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
# 启动请求生成任务(如果启用了受控生成)
|
|
114
|
+
if (self.start_requests and
|
|
115
|
+
self.settings.get_bool('ENABLE_CONTROLLED_REQUEST_GENERATION', False)):
|
|
116
|
+
generation_task = asyncio.create_task(
|
|
117
|
+
self._controlled_request_generation()
|
|
118
|
+
)
|
|
119
|
+
else:
|
|
120
|
+
# 传统方式处理启动请求
|
|
121
|
+
generation_task = asyncio.create_task(
|
|
122
|
+
self._traditional_request_generation()
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# 主爬取循环
|
|
126
|
+
while self.running:
|
|
127
|
+
# 获取并处理请求
|
|
128
|
+
if request := await self._get_next_request():
|
|
129
|
+
await self._crawl(request)
|
|
130
|
+
|
|
131
|
+
# 检查退出条件
|
|
132
|
+
if await self._should_exit():
|
|
133
|
+
break
|
|
134
|
+
|
|
135
|
+
# 短暂休息避免忙等
|
|
136
|
+
await asyncio.sleep(0.001)
|
|
137
|
+
|
|
138
|
+
finally:
|
|
139
|
+
# 清理生成任务
|
|
140
|
+
if generation_task and not generation_task.done():
|
|
141
|
+
generation_task.cancel()
|
|
142
|
+
try:
|
|
143
|
+
await generation_task
|
|
144
|
+
except asyncio.CancelledError:
|
|
145
|
+
pass
|
|
146
|
+
|
|
147
|
+
await self.close_spider()
|
|
148
|
+
|
|
149
|
+
async def _traditional_request_generation(self):
|
|
150
|
+
"""传统的请求生成方式(兼容旧版本)"""
|
|
151
|
+
while self.running:
|
|
152
|
+
try:
|
|
153
|
+
start_request = next(self.start_requests)
|
|
154
|
+
# 请求入队
|
|
155
|
+
await self.enqueue_request(start_request)
|
|
156
|
+
except StopIteration:
|
|
157
|
+
self.start_requests = None
|
|
158
|
+
break
|
|
159
|
+
except Exception as exp:
|
|
160
|
+
# 1、发去请求的request全部运行完毕
|
|
161
|
+
# 2、调度器是否空闲
|
|
162
|
+
# 3、下载器是否空闲
|
|
163
|
+
if not await self._exit():
|
|
164
|
+
continue
|
|
165
|
+
self.running = False
|
|
166
|
+
if self.start_requests is not None:
|
|
167
|
+
self.logger.error(f"启动请求时发生错误: {str(exp)}")
|
|
168
|
+
await asyncio.sleep(0.001)
|
|
169
|
+
|
|
170
|
+
async def _controlled_request_generation(self):
|
|
171
|
+
"""受控的请求生成(增强功能)"""
|
|
172
|
+
self.logger.info("🎛️ 启动受控请求生成")
|
|
173
|
+
|
|
174
|
+
batch = []
|
|
175
|
+
total_generated = 0
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
for request in self.start_requests:
|
|
179
|
+
batch.append(request)
|
|
180
|
+
|
|
181
|
+
# 批量处理
|
|
182
|
+
if len(batch) >= self.generation_batch_size:
|
|
183
|
+
generated = await self._process_generation_batch(batch)
|
|
184
|
+
total_generated += generated
|
|
185
|
+
batch = []
|
|
186
|
+
|
|
187
|
+
# 背压检查
|
|
188
|
+
if await self._should_pause_generation():
|
|
189
|
+
await self._wait_for_capacity()
|
|
190
|
+
|
|
191
|
+
# 处理剩余请求
|
|
192
|
+
if batch:
|
|
193
|
+
generated = await self._process_generation_batch(batch)
|
|
194
|
+
total_generated += generated
|
|
195
|
+
|
|
196
|
+
except Exception as e:
|
|
197
|
+
self.logger.error(f"❌ 请求生成失败: {e}")
|
|
198
|
+
|
|
199
|
+
finally:
|
|
200
|
+
self.start_requests = None
|
|
201
|
+
self.logger.info(f"🎉 请求生成完成,总计: {total_generated}")
|
|
202
|
+
|
|
203
|
+
async def _process_generation_batch(self, batch) -> int:
|
|
204
|
+
"""处理一批请求"""
|
|
205
|
+
generated = 0
|
|
206
|
+
|
|
207
|
+
for request in batch:
|
|
208
|
+
if not self.running:
|
|
209
|
+
break
|
|
210
|
+
|
|
211
|
+
# 等待队列有空间
|
|
212
|
+
while await self._is_queue_full() and self.running:
|
|
213
|
+
await asyncio.sleep(0.1)
|
|
214
|
+
|
|
215
|
+
if self.running:
|
|
216
|
+
await self.enqueue_request(request)
|
|
217
|
+
generated += 1
|
|
218
|
+
self._generation_stats['total_generated'] += 1
|
|
219
|
+
|
|
220
|
+
# 控制生成速度
|
|
221
|
+
if self.generation_interval > 0:
|
|
222
|
+
await asyncio.sleep(self.generation_interval)
|
|
223
|
+
|
|
224
|
+
return generated
|
|
225
|
+
|
|
226
|
+
async def _should_pause_generation(self) -> bool:
|
|
227
|
+
"""判断是否应该暂停生成"""
|
|
228
|
+
# 检查队列大小
|
|
229
|
+
if await self._is_queue_full():
|
|
230
|
+
return True
|
|
231
|
+
|
|
232
|
+
# 检查任务管理器负载
|
|
233
|
+
if self.task_manager:
|
|
234
|
+
current_tasks = len(self.task_manager.current_task)
|
|
235
|
+
if hasattr(self.task_manager, 'semaphore'):
|
|
236
|
+
max_concurrency = getattr(self.task_manager.semaphore, '_initial_value', 8)
|
|
237
|
+
if current_tasks >= max_concurrency * self.backpressure_ratio:
|
|
238
|
+
return True
|
|
239
|
+
|
|
240
|
+
return False
|
|
241
|
+
|
|
242
|
+
async def _is_queue_full(self) -> bool:
|
|
243
|
+
"""检查队列是否已满"""
|
|
244
|
+
if not self.scheduler:
|
|
245
|
+
return False
|
|
246
|
+
|
|
247
|
+
queue_size = len(self.scheduler)
|
|
248
|
+
return queue_size >= self.max_queue_size * self.backpressure_ratio
|
|
249
|
+
|
|
250
|
+
async def _wait_for_capacity(self):
|
|
251
|
+
"""等待系统有足够容量"""
|
|
252
|
+
self._generation_stats['backpressure_events'] += 1
|
|
253
|
+
self.logger.debug("⏸️ 触发背压,暂停请求生成")
|
|
254
|
+
|
|
255
|
+
wait_time = 0.1
|
|
256
|
+
max_wait = 2.0
|
|
257
|
+
|
|
258
|
+
while await self._should_pause_generation() and self.running:
|
|
259
|
+
await asyncio.sleep(wait_time)
|
|
260
|
+
wait_time = min(wait_time * 1.1, max_wait)
|
|
261
|
+
|
|
262
|
+
async def _open_spider(self):
|
|
263
|
+
asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
|
|
264
|
+
crawling = asyncio.create_task(self.crawl())
|
|
265
|
+
await crawling
|
|
266
|
+
|
|
267
|
+
async def _crawl(self, request):
|
|
268
|
+
# TODO 实现并发
|
|
269
|
+
async def crawl_task():
|
|
270
|
+
outputs = await self._fetch(request)
|
|
271
|
+
# TODO 处理output
|
|
272
|
+
if outputs:
|
|
273
|
+
await self._handle_spider_output(outputs)
|
|
274
|
+
|
|
275
|
+
# 使用异步任务创建,遵守并发限制
|
|
276
|
+
await self.task_manager.create_task(crawl_task())
|
|
277
|
+
|
|
278
|
+
async def _fetch(self, request):
|
|
279
|
+
async def _successful(_response):
|
|
280
|
+
callback: Callable = request.callback or self.spider.parse
|
|
281
|
+
if _outputs := callback(_response):
|
|
282
|
+
if iscoroutine(_outputs):
|
|
283
|
+
await _outputs
|
|
284
|
+
else:
|
|
285
|
+
return transform(_outputs, _response)
|
|
286
|
+
|
|
287
|
+
_response = await self.downloader.fetch(request)
|
|
288
|
+
if _response is None:
|
|
289
|
+
return None
|
|
290
|
+
output = await _successful(_response)
|
|
291
|
+
return output
|
|
292
|
+
|
|
293
|
+
async def enqueue_request(self, start_request):
|
|
294
|
+
await self._schedule_request(start_request)
|
|
295
|
+
|
|
296
|
+
async def _schedule_request(self, request):
|
|
297
|
+
# TODO 去重
|
|
298
|
+
if await self.scheduler.enqueue_request(request):
|
|
299
|
+
asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
|
|
300
|
+
|
|
301
|
+
async def _get_next_request(self):
|
|
302
|
+
return await self.scheduler.next_request()
|
|
303
|
+
|
|
304
|
+
async def _handle_spider_output(self, outputs):
|
|
305
|
+
async for spider_output in outputs:
|
|
306
|
+
if isinstance(spider_output, (Request, Item)):
|
|
307
|
+
await self.processor.enqueue(spider_output)
|
|
308
|
+
elif isinstance(spider_output, Exception):
|
|
309
|
+
asyncio.create_task(
|
|
310
|
+
self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
|
|
311
|
+
)
|
|
312
|
+
raise spider_output
|
|
313
|
+
else:
|
|
314
|
+
raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
|
|
315
|
+
|
|
316
|
+
async def _exit(self):
|
|
317
|
+
if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
|
|
318
|
+
return True
|
|
319
|
+
return False
|
|
320
|
+
|
|
321
|
+
async def _should_exit(self) -> bool:
|
|
322
|
+
"""检查是否应该退出(增强版本)"""
|
|
323
|
+
# 没有启动请求,且所有队列都空闲
|
|
324
|
+
if self.start_requests is None:
|
|
325
|
+
# 使用异步的idle检查方法以获得更精确的结果
|
|
326
|
+
scheduler_idle = await self.scheduler.async_idle() if hasattr(self.scheduler, 'async_idle') else self.scheduler.idle()
|
|
327
|
+
|
|
328
|
+
if (scheduler_idle and
|
|
329
|
+
self.downloader.idle() and
|
|
330
|
+
self.task_manager.all_done() and
|
|
331
|
+
self.processor.idle()):
|
|
332
|
+
# 增加额外检查确保所有任务都完成
|
|
333
|
+
await asyncio.sleep(0.1) # 短暂等待确保没有新的任务加入
|
|
334
|
+
if (await self.scheduler.async_idle() and
|
|
335
|
+
self.downloader.idle() and
|
|
336
|
+
self.task_manager.all_done() and
|
|
337
|
+
self.processor.idle()):
|
|
338
|
+
return True
|
|
339
|
+
|
|
340
|
+
return False
|
|
341
|
+
|
|
342
|
+
async def close_spider(self):
|
|
343
|
+
await asyncio.gather(*self.task_manager.current_task)
|
|
344
|
+
await self.scheduler.close()
|
|
345
|
+
await self.downloader.close()
|
|
346
|
+
if self.normal:
|
|
347
|
+
await self.crawler.close()
|
|
348
|
+
|
|
349
|
+
def get_generation_stats(self) -> dict:
|
|
350
|
+
"""获取生成统计"""
|
|
351
|
+
return {
|
|
352
|
+
**self._generation_stats,
|
|
353
|
+
'queue_size': len(self.scheduler) if self.scheduler else 0,
|
|
354
|
+
'active_tasks': len(self.task_manager.current_task) if self.task_manager else 0
|
|
346
355
|
}
|