crawlo 1.1.0__py3-none-any.whl → 1.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of crawlo might be problematic. Click here for more details.
- crawlo/__init__.py +34 -24
- crawlo/__version__.py +1 -1
- crawlo/cli.py +40 -40
- crawlo/commands/__init__.py +13 -13
- crawlo/commands/check.py +594 -155
- crawlo/commands/genspider.py +152 -111
- crawlo/commands/list.py +156 -119
- crawlo/commands/run.py +285 -170
- crawlo/commands/startproject.py +196 -101
- crawlo/commands/stats.py +188 -167
- crawlo/commands/utils.py +187 -0
- crawlo/config.py +280 -0
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +171 -158
- crawlo/core/enhanced_engine.py +190 -0
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +162 -57
- crawlo/crawler.py +1028 -493
- crawlo/downloader/__init__.py +242 -78
- crawlo/downloader/aiohttp_downloader.py +212 -199
- crawlo/downloader/cffi_downloader.py +252 -277
- crawlo/downloader/httpx_downloader.py +257 -246
- crawlo/event.py +11 -11
- crawlo/exceptions.py +78 -78
- crawlo/extension/__init__.py +31 -31
- crawlo/extension/log_interval.py +49 -49
- crawlo/extension/log_stats.py +44 -44
- crawlo/extension/logging_extension.py +34 -34
- crawlo/filters/__init__.py +154 -37
- crawlo/filters/aioredis_filter.py +242 -150
- crawlo/filters/memory_filter.py +269 -202
- 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 +248 -245
- 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 +125 -90
- crawlo/mode_manager.py +201 -0
- crawlo/network/__init__.py +21 -7
- crawlo/network/request.py +311 -203
- crawlo/network/response.py +269 -166
- crawlo/pipelines/__init__.py +13 -13
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/pipelines/mongo_pipeline.py +116 -116
- crawlo/pipelines/mysql_pipeline.py +195 -195
- crawlo/pipelines/pipeline_manager.py +56 -56
- crawlo/project.py +153 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +304 -0
- crawlo/queue/redis_priority_queue.py +192 -0
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +226 -169
- crawlo/settings/setting_manager.py +99 -99
- crawlo/spider/__init__.py +639 -129
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +106 -106
- crawlo/task_manager.py +30 -27
- 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 +87 -76
- crawlo/templates/project/pipelines.py.tmpl +336 -64
- crawlo/templates/project/run.py.tmpl +239 -0
- crawlo/templates/project/settings.py.tmpl +248 -54
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/spider/spider.py.tmpl +178 -32
- crawlo/utils/__init__.py +7 -7
- crawlo/utils/controlled_spider_mixin.py +336 -0
- crawlo/utils/date_tools.py +233 -233
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +287 -0
- crawlo/utils/large_scale_helper.py +344 -0
- crawlo/utils/log.py +128 -128
- crawlo/utils/queue_helper.py +176 -0
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +220 -0
- 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.1.2.dist-info/METADATA +567 -0
- crawlo-1.1.2.dist-info/RECORD +108 -0
- examples/__init__.py +7 -0
- tests/__init__.py +7 -7
- tests/test_final_validation.py +154 -0
- 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_redis_config.py +29 -0
- tests/test_redis_queue.py +225 -0
- tests/test_request_serialization.py +71 -0
- tests/test_scheduler.py +242 -0
- crawlo/pipelines/mysql_batch_pipline.py +0 -273
- crawlo/utils/concurrency_manager.py +0 -125
- crawlo/utils/pqueue.py +0 -174
- crawlo/utils/project.py +0 -197
- crawlo-1.1.0.dist-info/METADATA +0 -49
- crawlo-1.1.0.dist-info/RECORD +0 -97
- examples/gxb/items.py +0 -36
- examples/gxb/run.py +0 -16
- examples/gxb/settings.py +0 -72
- examples/gxb/spider/__init__.py +0 -2
- examples/gxb/spider/miit_spider.py +0 -180
- examples/gxb/spider/telecom_device.py +0 -129
- {examples/gxb → crawlo/queue}/__init__.py +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
crawlo/config.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawlo 配置工厂
|
|
5
|
+
===============
|
|
6
|
+
提供优雅的配置方式,让用户能够轻松选择运行模式。
|
|
7
|
+
|
|
8
|
+
使用示例:
|
|
9
|
+
# 单机模式(默认)
|
|
10
|
+
config = CrawloConfig.standalone()
|
|
11
|
+
|
|
12
|
+
# 分布式模式
|
|
13
|
+
config = CrawloConfig.distributed(redis_host='192.168.1.100')
|
|
14
|
+
|
|
15
|
+
# 自动检测模式
|
|
16
|
+
config = CrawloConfig.auto()
|
|
17
|
+
|
|
18
|
+
# 从环境变量
|
|
19
|
+
config = CrawloConfig.from_env()
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from typing import Dict, Any, Optional, Union
|
|
23
|
+
import os
|
|
24
|
+
from crawlo.mode_manager import ModeManager, standalone_mode, distributed_mode, auto_mode, from_env
|
|
25
|
+
from crawlo.utils.log import get_logger
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CrawloConfig:
|
|
29
|
+
"""Crawlo 配置工厂类"""
|
|
30
|
+
|
|
31
|
+
def __init__(self, settings: Dict[str, Any]):
|
|
32
|
+
self.settings = settings
|
|
33
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
34
|
+
|
|
35
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
36
|
+
"""获取配置项"""
|
|
37
|
+
return self.settings.get(key, default)
|
|
38
|
+
|
|
39
|
+
def set(self, key: str, value: Any) -> 'CrawloConfig':
|
|
40
|
+
"""设置配置项(链式调用)"""
|
|
41
|
+
self.settings[key] = value
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
def update(self, settings: Dict[str, Any]) -> 'CrawloConfig':
|
|
45
|
+
"""更新配置(链式调用)"""
|
|
46
|
+
self.settings.update(settings)
|
|
47
|
+
return self
|
|
48
|
+
|
|
49
|
+
def set_concurrency(self, concurrency: int) -> 'CrawloConfig':
|
|
50
|
+
"""设置并发数"""
|
|
51
|
+
return self.set('CONCURRENCY', concurrency)
|
|
52
|
+
|
|
53
|
+
def set_delay(self, delay: float) -> 'CrawloConfig':
|
|
54
|
+
"""设置请求延迟"""
|
|
55
|
+
return self.set('DOWNLOAD_DELAY', delay)
|
|
56
|
+
|
|
57
|
+
def enable_debug(self) -> 'CrawloConfig':
|
|
58
|
+
"""启用调试模式"""
|
|
59
|
+
return self.set('LOG_LEVEL', 'DEBUG')
|
|
60
|
+
|
|
61
|
+
def enable_mysql(self) -> 'CrawloConfig':
|
|
62
|
+
"""启用 MySQL 存储"""
|
|
63
|
+
pipelines = self.get('PIPELINES', [])
|
|
64
|
+
if 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline' not in pipelines:
|
|
65
|
+
pipelines.append('crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline')
|
|
66
|
+
return self.set('PIPELINES', pipelines)
|
|
67
|
+
|
|
68
|
+
def set_redis_host(self, host: str) -> 'CrawloConfig':
|
|
69
|
+
"""设置 Redis 主机"""
|
|
70
|
+
return self.set('REDIS_HOST', host)
|
|
71
|
+
|
|
72
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
73
|
+
"""转换为字典"""
|
|
74
|
+
return self.settings.copy()
|
|
75
|
+
|
|
76
|
+
def print_summary(self) -> 'CrawloConfig':
|
|
77
|
+
"""打印配置摘要"""
|
|
78
|
+
mode_info = {
|
|
79
|
+
'memory': '🏠 单机模式',
|
|
80
|
+
'redis': '🌐 分布式模式',
|
|
81
|
+
'auto': '🤖 自动检测模式'
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
queue_type = self.settings.get('QUEUE_TYPE', 'memory')
|
|
85
|
+
filter_class = self.settings.get('FILTER_CLASS', '').split('.')[-1]
|
|
86
|
+
concurrency = self.settings.get('CONCURRENCY', 8)
|
|
87
|
+
|
|
88
|
+
print("=" * 50)
|
|
89
|
+
print(f"📋 Crawlo 配置摘要")
|
|
90
|
+
print("=" * 50)
|
|
91
|
+
print(f"运行模式: {mode_info.get(queue_type, queue_type)}")
|
|
92
|
+
print(f"队列类型: {queue_type}")
|
|
93
|
+
print(f"去重方式: {filter_class}")
|
|
94
|
+
print(f"并发数量: {concurrency}")
|
|
95
|
+
|
|
96
|
+
if queue_type == 'redis':
|
|
97
|
+
redis_host = self.settings.get('REDIS_HOST', 'localhost')
|
|
98
|
+
print(f"Redis 服务器: {redis_host}")
|
|
99
|
+
|
|
100
|
+
print("=" * 50)
|
|
101
|
+
return self
|
|
102
|
+
|
|
103
|
+
# ==================== 静态工厂方法 ====================
|
|
104
|
+
|
|
105
|
+
@staticmethod
|
|
106
|
+
def standalone(
|
|
107
|
+
concurrency: int = 8,
|
|
108
|
+
download_delay: float = 1.0,
|
|
109
|
+
**kwargs
|
|
110
|
+
) -> 'CrawloConfig':
|
|
111
|
+
"""
|
|
112
|
+
创建单机模式配置
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
concurrency: 并发数
|
|
116
|
+
download_delay: 下载延迟
|
|
117
|
+
**kwargs: 其他配置项
|
|
118
|
+
"""
|
|
119
|
+
settings = standalone_mode(
|
|
120
|
+
CONCURRENCY=concurrency,
|
|
121
|
+
DOWNLOAD_DELAY=download_delay,
|
|
122
|
+
**kwargs
|
|
123
|
+
)
|
|
124
|
+
return CrawloConfig(settings)
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def distributed(
|
|
128
|
+
redis_host: str = '127.0.0.1',
|
|
129
|
+
redis_port: int = 6379,
|
|
130
|
+
redis_password: Optional[str] = None,
|
|
131
|
+
project_name: str = 'crawlo',
|
|
132
|
+
concurrency: int = 16,
|
|
133
|
+
download_delay: float = 1.0,
|
|
134
|
+
**kwargs
|
|
135
|
+
) -> 'CrawloConfig':
|
|
136
|
+
"""
|
|
137
|
+
创建分布式模式配置
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
redis_host: Redis 服务器地址
|
|
141
|
+
redis_port: Redis 端口
|
|
142
|
+
redis_password: Redis 密码
|
|
143
|
+
project_name: 项目名称(用于命名空间)
|
|
144
|
+
concurrency: 并发数
|
|
145
|
+
download_delay: 下载延迟
|
|
146
|
+
**kwargs: 其他配置项
|
|
147
|
+
"""
|
|
148
|
+
settings = distributed_mode(
|
|
149
|
+
redis_host=redis_host,
|
|
150
|
+
redis_port=redis_port,
|
|
151
|
+
redis_password=redis_password,
|
|
152
|
+
project_name=project_name,
|
|
153
|
+
CONCURRENCY=concurrency,
|
|
154
|
+
DOWNLOAD_DELAY=download_delay,
|
|
155
|
+
**kwargs
|
|
156
|
+
)
|
|
157
|
+
return CrawloConfig(settings)
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def auto(
|
|
161
|
+
concurrency: int = 12,
|
|
162
|
+
download_delay: float = 1.0,
|
|
163
|
+
**kwargs
|
|
164
|
+
) -> 'CrawloConfig':
|
|
165
|
+
"""
|
|
166
|
+
创建自动检测模式配置
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
concurrency: 并发数
|
|
170
|
+
download_delay: 下载延迟
|
|
171
|
+
**kwargs: 其他配置项
|
|
172
|
+
"""
|
|
173
|
+
settings = auto_mode(
|
|
174
|
+
CONCURRENCY=concurrency,
|
|
175
|
+
DOWNLOAD_DELAY=download_delay,
|
|
176
|
+
**kwargs
|
|
177
|
+
)
|
|
178
|
+
return CrawloConfig(settings)
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def from_env(default_mode: str = 'standalone') -> 'CrawloConfig':
|
|
182
|
+
"""
|
|
183
|
+
从环境变量创建配置
|
|
184
|
+
|
|
185
|
+
支持的环境变量:
|
|
186
|
+
- CRAWLO_MODE: 运行模式 (standalone/distributed/auto)
|
|
187
|
+
- REDIS_HOST: Redis 主机
|
|
188
|
+
- REDIS_PORT: Redis 端口
|
|
189
|
+
- REDIS_PASSWORD: Redis 密码
|
|
190
|
+
- CONCURRENCY: 并发数
|
|
191
|
+
- PROJECT_NAME: 项目名称
|
|
192
|
+
"""
|
|
193
|
+
settings = from_env(default_mode)
|
|
194
|
+
return CrawloConfig(settings)
|
|
195
|
+
|
|
196
|
+
@staticmethod
|
|
197
|
+
def custom(settings: Dict[str, Any]) -> 'CrawloConfig':
|
|
198
|
+
"""
|
|
199
|
+
创建自定义配置
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
settings: 自定义配置字典
|
|
203
|
+
"""
|
|
204
|
+
return CrawloConfig(settings)
|
|
205
|
+
|
|
206
|
+
@staticmethod
|
|
207
|
+
def presets() -> 'Presets':
|
|
208
|
+
"""获取预设配置对象"""
|
|
209
|
+
return Presets()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
# ==================== 便利函数 ====================
|
|
213
|
+
|
|
214
|
+
def create_config(
|
|
215
|
+
mode: str = 'standalone',
|
|
216
|
+
**kwargs
|
|
217
|
+
) -> CrawloConfig:
|
|
218
|
+
"""
|
|
219
|
+
便利函数:创建配置
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
mode: 运行模式 ('standalone', 'distributed', 'auto')
|
|
223
|
+
**kwargs: 配置参数
|
|
224
|
+
"""
|
|
225
|
+
if mode.lower() == 'standalone':
|
|
226
|
+
return CrawloConfig.standalone(**kwargs)
|
|
227
|
+
elif mode.lower() == 'distributed':
|
|
228
|
+
return CrawloConfig.distributed(**kwargs)
|
|
229
|
+
elif mode.lower() == 'auto':
|
|
230
|
+
return CrawloConfig.auto(**kwargs)
|
|
231
|
+
else:
|
|
232
|
+
raise ValueError(f"不支持的运行模式: {mode}")
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# ==================== 预设配置 ====================
|
|
236
|
+
|
|
237
|
+
class Presets:
|
|
238
|
+
"""预设配置类"""
|
|
239
|
+
|
|
240
|
+
@staticmethod
|
|
241
|
+
def development() -> CrawloConfig:
|
|
242
|
+
"""开发环境配置"""
|
|
243
|
+
return CrawloConfig.standalone(
|
|
244
|
+
concurrency=4,
|
|
245
|
+
download_delay=2.0,
|
|
246
|
+
LOG_LEVEL='DEBUG',
|
|
247
|
+
STATS_DUMP=True
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def production() -> CrawloConfig:
|
|
252
|
+
"""生产环境配置"""
|
|
253
|
+
return CrawloConfig.auto(
|
|
254
|
+
concurrency=16,
|
|
255
|
+
download_delay=1.0,
|
|
256
|
+
LOG_LEVEL='INFO',
|
|
257
|
+
RETRY_TIMES=5
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
@staticmethod
|
|
261
|
+
def large_scale(redis_host: str, project_name: str) -> CrawloConfig:
|
|
262
|
+
"""大规模分布式配置"""
|
|
263
|
+
return CrawloConfig.distributed(
|
|
264
|
+
redis_host=redis_host,
|
|
265
|
+
project_name=project_name,
|
|
266
|
+
concurrency=32,
|
|
267
|
+
download_delay=0.5,
|
|
268
|
+
SCHEDULER_MAX_QUEUE_SIZE=10000,
|
|
269
|
+
LARGE_SCALE_BATCH_SIZE=2000
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
@staticmethod
|
|
273
|
+
def gentle() -> CrawloConfig:
|
|
274
|
+
"""温和模式配置(避免被封)"""
|
|
275
|
+
return CrawloConfig.standalone(
|
|
276
|
+
concurrency=2,
|
|
277
|
+
download_delay=3.0,
|
|
278
|
+
RANDOMNESS=True,
|
|
279
|
+
RANDOM_RANGE=(2.0, 5.0)
|
|
280
|
+
)
|
crawlo/core/__init__.py
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
crawlo/core/engine.py
CHANGED
|
@@ -1,159 +1,172 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
import asyncio
|
|
4
|
-
from inspect import iscoroutine
|
|
5
|
-
from typing import Optional, Generator, Callable
|
|
6
|
-
|
|
7
|
-
from crawlo import Request, Item
|
|
8
|
-
from crawlo.spider import Spider
|
|
9
|
-
from crawlo.utils.log import get_logger
|
|
10
|
-
from crawlo.exceptions import OutputError
|
|
11
|
-
from crawlo.core.scheduler import Scheduler
|
|
12
|
-
from crawlo.core.processor import Processor
|
|
13
|
-
from crawlo.task_manager import TaskManager
|
|
14
|
-
from crawlo.
|
|
15
|
-
from crawlo.downloader import DownloaderBase
|
|
16
|
-
from crawlo.utils.func_tools import transform
|
|
17
|
-
from crawlo.event import spider_opened, spider_error, request_scheduled
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
class Engine(object):
|
|
21
|
-
|
|
22
|
-
def __init__(self, crawler):
|
|
23
|
-
self.running = False
|
|
24
|
-
self.normal = True
|
|
25
|
-
self.crawler = crawler
|
|
26
|
-
self.settings = crawler.settings
|
|
27
|
-
self.spider: Optional[Spider] = None
|
|
28
|
-
self.downloader: Optional[DownloaderBase] = None
|
|
29
|
-
self.scheduler: Optional[Scheduler] = None
|
|
30
|
-
self.processor: Optional[Processor] = None
|
|
31
|
-
self.start_requests: Optional[Generator] = None
|
|
32
|
-
self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
|
|
33
|
-
|
|
34
|
-
self.logger = get_logger(name=self.__class__.__name__)
|
|
35
|
-
|
|
36
|
-
def _get_downloader_cls(self):
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
self.
|
|
58
|
-
|
|
59
|
-
self.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
self.
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
self.
|
|
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
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
import asyncio
|
|
4
|
+
from inspect import iscoroutine
|
|
5
|
+
from typing import Optional, Generator, Callable
|
|
6
|
+
|
|
7
|
+
from crawlo import Request, Item
|
|
8
|
+
from crawlo.spider import Spider
|
|
9
|
+
from crawlo.utils.log import get_logger
|
|
10
|
+
from crawlo.exceptions import OutputError
|
|
11
|
+
from crawlo.core.scheduler import Scheduler
|
|
12
|
+
from crawlo.core.processor import Processor
|
|
13
|
+
from crawlo.task_manager import TaskManager
|
|
14
|
+
from crawlo.project import load_class
|
|
15
|
+
from crawlo.downloader import DownloaderBase
|
|
16
|
+
from crawlo.utils.func_tools import transform
|
|
17
|
+
from crawlo.event import spider_opened, spider_error, request_scheduled
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Engine(object):
|
|
21
|
+
|
|
22
|
+
def __init__(self, crawler):
|
|
23
|
+
self.running = False
|
|
24
|
+
self.normal = True
|
|
25
|
+
self.crawler = crawler
|
|
26
|
+
self.settings = crawler.settings
|
|
27
|
+
self.spider: Optional[Spider] = None
|
|
28
|
+
self.downloader: Optional[DownloaderBase] = None
|
|
29
|
+
self.scheduler: Optional[Scheduler] = None
|
|
30
|
+
self.processor: Optional[Processor] = None
|
|
31
|
+
self.start_requests: Optional[Generator] = None
|
|
32
|
+
self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
|
|
33
|
+
|
|
34
|
+
self.logger = get_logger(name=self.__class__.__name__)
|
|
35
|
+
|
|
36
|
+
def _get_downloader_cls(self):
|
|
37
|
+
"""获取下载器类,支持多种配置方式"""
|
|
38
|
+
# 方式1: 使用 DOWNLOADER_TYPE 简化名称(推荐)
|
|
39
|
+
downloader_type = self.settings.get('DOWNLOADER_TYPE')
|
|
40
|
+
if downloader_type:
|
|
41
|
+
try:
|
|
42
|
+
from crawlo.downloader import get_downloader_class
|
|
43
|
+
downloader_cls = get_downloader_class(downloader_type)
|
|
44
|
+
self.logger.debug(f"使用下载器类型: {downloader_type} -> {downloader_cls.__name__}")
|
|
45
|
+
return downloader_cls
|
|
46
|
+
except (ImportError, ValueError) as e:
|
|
47
|
+
self.logger.warning(f"无法使用下载器类型 '{downloader_type}': {e},回退到默认配置")
|
|
48
|
+
|
|
49
|
+
# 方式2: 使用 DOWNLOADER 完整类路径(兼容旧版本)
|
|
50
|
+
downloader_cls = load_class(self.settings.get('DOWNLOADER'))
|
|
51
|
+
if not issubclass(downloader_cls, DownloaderBase):
|
|
52
|
+
raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
|
|
53
|
+
return downloader_cls
|
|
54
|
+
|
|
55
|
+
def engine_start(self):
|
|
56
|
+
self.running = True
|
|
57
|
+
self.logger.info(
|
|
58
|
+
f"Crawlo (version {self.settings.get_float('VERSION')}) started. "
|
|
59
|
+
f"(project name : {self.settings.get('PROJECT_NAME')})"
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
async def start_spider(self, spider):
|
|
63
|
+
self.spider = spider
|
|
64
|
+
|
|
65
|
+
self.scheduler = Scheduler.create_instance(self.crawler)
|
|
66
|
+
if hasattr(self.scheduler, 'open'):
|
|
67
|
+
await self.scheduler.open()
|
|
68
|
+
|
|
69
|
+
downloader_cls = self._get_downloader_cls()
|
|
70
|
+
self.downloader = downloader_cls(self.crawler)
|
|
71
|
+
if hasattr(self.downloader, 'open'):
|
|
72
|
+
self.downloader.open()
|
|
73
|
+
|
|
74
|
+
self.processor = Processor(self.crawler)
|
|
75
|
+
if hasattr(self.processor, 'open'):
|
|
76
|
+
self.processor.open()
|
|
77
|
+
|
|
78
|
+
self.start_requests = iter(spider.start_requests())
|
|
79
|
+
await self._open_spider()
|
|
80
|
+
|
|
81
|
+
async def crawl(self):
|
|
82
|
+
"""
|
|
83
|
+
Crawl the spider
|
|
84
|
+
"""
|
|
85
|
+
while self.running:
|
|
86
|
+
if request := await self._get_next_request():
|
|
87
|
+
await self._crawl(request)
|
|
88
|
+
try:
|
|
89
|
+
start_request = next(self.start_requests)
|
|
90
|
+
except StopIteration:
|
|
91
|
+
self.start_requests = None
|
|
92
|
+
except Exception as exp:
|
|
93
|
+
# 1、发去请求的request全部运行完毕
|
|
94
|
+
# 2、调度器是否空闲
|
|
95
|
+
# 3、下载器是否空闲
|
|
96
|
+
if not await self._exit():
|
|
97
|
+
continue
|
|
98
|
+
self.running = False
|
|
99
|
+
if self.start_requests is not None:
|
|
100
|
+
self.logger.error(f"启动请求时发生错误: {str(exp)}")
|
|
101
|
+
else:
|
|
102
|
+
# 请求入队
|
|
103
|
+
await self.enqueue_request(start_request)
|
|
104
|
+
|
|
105
|
+
if not self.running:
|
|
106
|
+
await self.close_spider()
|
|
107
|
+
|
|
108
|
+
async def _open_spider(self):
|
|
109
|
+
asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
|
|
110
|
+
crawling = asyncio.create_task(self.crawl())
|
|
111
|
+
await crawling
|
|
112
|
+
|
|
113
|
+
async def _crawl(self, request):
|
|
114
|
+
# TODO 实现并发
|
|
115
|
+
async def crawl_task():
|
|
116
|
+
outputs = await self._fetch(request)
|
|
117
|
+
# TODO 处理output
|
|
118
|
+
if outputs:
|
|
119
|
+
await self._handle_spider_output(outputs)
|
|
120
|
+
|
|
121
|
+
# 使用异步任务创建,遵守并发限制
|
|
122
|
+
await self.task_manager.create_task(crawl_task())
|
|
123
|
+
|
|
124
|
+
async def _fetch(self, request):
|
|
125
|
+
async def _successful(_response):
|
|
126
|
+
callback: Callable = request.callback or self.spider.parse
|
|
127
|
+
if _outputs := callback(_response):
|
|
128
|
+
if iscoroutine(_outputs):
|
|
129
|
+
await _outputs
|
|
130
|
+
else:
|
|
131
|
+
return transform(_outputs, _response)
|
|
132
|
+
|
|
133
|
+
_response = await self.downloader.fetch(request)
|
|
134
|
+
if _response is None:
|
|
135
|
+
return None
|
|
136
|
+
output = await _successful(_response)
|
|
137
|
+
return output
|
|
138
|
+
|
|
139
|
+
async def enqueue_request(self, start_request):
|
|
140
|
+
await self._schedule_request(start_request)
|
|
141
|
+
|
|
142
|
+
async def _schedule_request(self, request):
|
|
143
|
+
# TODO 去重
|
|
144
|
+
if await self.scheduler.enqueue_request(request):
|
|
145
|
+
asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
|
|
146
|
+
|
|
147
|
+
async def _get_next_request(self):
|
|
148
|
+
return await self.scheduler.next_request()
|
|
149
|
+
|
|
150
|
+
async def _handle_spider_output(self, outputs):
|
|
151
|
+
async for spider_output in outputs:
|
|
152
|
+
if isinstance(spider_output, (Request, Item)):
|
|
153
|
+
await self.processor.enqueue(spider_output)
|
|
154
|
+
elif isinstance(spider_output, Exception):
|
|
155
|
+
asyncio.create_task(
|
|
156
|
+
self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
|
|
157
|
+
)
|
|
158
|
+
raise spider_output
|
|
159
|
+
else:
|
|
160
|
+
raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
|
|
161
|
+
|
|
162
|
+
async def _exit(self):
|
|
163
|
+
if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
|
|
164
|
+
return True
|
|
165
|
+
return False
|
|
166
|
+
|
|
167
|
+
async def close_spider(self):
|
|
168
|
+
await asyncio.gather(*self.task_manager.current_task)
|
|
169
|
+
await self.scheduler.close()
|
|
170
|
+
await self.downloader.close()
|
|
171
|
+
if self.normal:
|
|
159
172
|
await self.crawler.close()
|