crawlo 1.3.2__py3-none-any.whl → 1.3.4__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 +24 -0
- crawlo/__version__.py +1 -1
- crawlo/commands/run.py +58 -32
- crawlo/core/__init__.py +44 -0
- crawlo/core/engine.py +119 -45
- crawlo/core/scheduler.py +4 -3
- crawlo/crawler.py +603 -1133
- crawlo/downloader/aiohttp_downloader.py +4 -2
- crawlo/extension/__init__.py +1 -1
- crawlo/extension/logging_extension.py +23 -7
- crawlo/factories/__init__.py +28 -0
- crawlo/factories/base.py +69 -0
- crawlo/factories/crawler.py +104 -0
- crawlo/factories/registry.py +85 -0
- crawlo/filters/aioredis_filter.py +25 -2
- crawlo/framework.py +292 -0
- crawlo/initialization/__init__.py +40 -0
- crawlo/initialization/built_in.py +426 -0
- crawlo/initialization/context.py +142 -0
- crawlo/initialization/core.py +194 -0
- crawlo/initialization/phases.py +149 -0
- crawlo/initialization/registry.py +146 -0
- crawlo/items/base.py +2 -1
- crawlo/logging/__init__.py +38 -0
- crawlo/logging/config.py +97 -0
- crawlo/logging/factory.py +129 -0
- crawlo/logging/manager.py +112 -0
- crawlo/middleware/middleware_manager.py +1 -1
- crawlo/middleware/offsite.py +1 -1
- crawlo/mode_manager.py +26 -1
- crawlo/pipelines/pipeline_manager.py +2 -1
- crawlo/project.py +76 -46
- crawlo/queue/pqueue.py +11 -5
- crawlo/queue/queue_manager.py +143 -19
- crawlo/queue/redis_priority_queue.py +69 -49
- crawlo/settings/default_settings.py +110 -14
- crawlo/settings/setting_manager.py +29 -13
- crawlo/spider/__init__.py +34 -16
- crawlo/stats_collector.py +17 -3
- crawlo/task_manager.py +112 -3
- crawlo/templates/project/settings.py.tmpl +103 -202
- crawlo/templates/project/settings_distributed.py.tmpl +122 -135
- crawlo/templates/project/settings_gentle.py.tmpl +149 -43
- crawlo/templates/project/settings_high_performance.py.tmpl +127 -90
- crawlo/templates/project/settings_minimal.py.tmpl +46 -15
- crawlo/templates/project/settings_simple.py.tmpl +138 -75
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -1
- crawlo/templates/run.py.tmpl +10 -14
- crawlo/templates/spiders_init.py.tmpl +10 -0
- crawlo/tools/network_diagnostic.py +365 -0
- crawlo/utils/class_loader.py +26 -0
- crawlo/utils/error_handler.py +76 -35
- crawlo/utils/log.py +41 -144
- crawlo/utils/redis_connection_pool.py +43 -6
- crawlo/utils/request_serializer.py +8 -1
- {crawlo-1.3.2.dist-info → crawlo-1.3.4.dist-info}/METADATA +120 -14
- {crawlo-1.3.2.dist-info → crawlo-1.3.4.dist-info}/RECORD +104 -45
- tests/authenticated_proxy_example.py +2 -2
- tests/baidu_performance_test.py +109 -0
- tests/baidu_test.py +60 -0
- tests/comprehensive_framework_test.py +213 -0
- tests/comprehensive_test.py +82 -0
- tests/comprehensive_testing_summary.md +187 -0
- tests/debug_configure.py +70 -0
- tests/debug_framework_logger.py +85 -0
- tests/debug_log_levels.py +64 -0
- tests/distributed_test.py +67 -0
- tests/distributed_test_debug.py +77 -0
- tests/final_command_test_report.md +0 -0
- tests/final_comprehensive_test.py +152 -0
- tests/final_validation_test.py +183 -0
- tests/framework_performance_test.py +203 -0
- tests/optimized_performance_test.py +212 -0
- tests/performance_comparison.py +246 -0
- tests/queue_blocking_test.py +114 -0
- tests/queue_test.py +90 -0
- tests/scrapy_comparison/ofweek_scrapy.py +139 -0
- tests/scrapy_comparison/scrapy_test.py +134 -0
- tests/simple_command_test.py +120 -0
- tests/simple_crawlo_test.py +128 -0
- tests/simple_log_test.py +58 -0
- tests/simple_optimization_test.py +129 -0
- tests/simple_spider_test.py +50 -0
- tests/simple_test.py +48 -0
- tests/test_all_commands.py +231 -0
- tests/test_batch_processor.py +179 -0
- tests/test_component_factory.py +175 -0
- tests/test_controlled_spider_mixin.py +80 -0
- tests/test_enhanced_error_handler_comprehensive.py +246 -0
- tests/test_factories.py +253 -0
- tests/test_framework_logger.py +67 -0
- tests/test_framework_startup.py +65 -0
- tests/test_large_scale_config.py +113 -0
- tests/test_large_scale_helper.py +236 -0
- tests/test_mode_change.py +73 -0
- tests/test_mode_consistency.py +1 -1
- tests/test_performance_monitor.py +116 -0
- tests/test_queue_empty_check.py +42 -0
- tests/untested_features_report.md +139 -0
- tests/verify_debug.py +52 -0
- tests/verify_log_fix.py +112 -0
- tests/DOUBLE_CRAWLO_PREFIX_FIX_REPORT.md +0 -82
- {crawlo-1.3.2.dist-info → crawlo-1.3.4.dist-info}/WHEEL +0 -0
- {crawlo-1.3.2.dist-info → crawlo-1.3.4.dist-info}/entry_points.txt +0 -0
- {crawlo-1.3.2.dist-info → crawlo-1.3.4.dist-info}/top_level.txt +0 -0
|
@@ -39,8 +39,8 @@ class AioHttpDownloader(DownloaderBase):
|
|
|
39
39
|
# 读取配置
|
|
40
40
|
timeout_secs = self.crawler.settings.get_int("DOWNLOAD_TIMEOUT", 30)
|
|
41
41
|
verify_ssl = self.crawler.settings.get_bool("VERIFY_SSL", True)
|
|
42
|
-
pool_limit = self.crawler.settings.get_int("CONNECTION_POOL_LIMIT",
|
|
43
|
-
pool_per_host = self.crawler.settings.get_int("CONNECTION_POOL_LIMIT_PER_HOST",
|
|
42
|
+
pool_limit = self.crawler.settings.get_int("CONNECTION_POOL_LIMIT", 300) # 从200增加到300
|
|
43
|
+
pool_per_host = self.crawler.settings.get_int("CONNECTION_POOL_LIMIT_PER_HOST", 100) # 从50增加到100
|
|
44
44
|
self.max_download_size = self.crawler.settings.get_int("DOWNLOAD_MAXSIZE", 10 * 1024 * 1024) # 10MB
|
|
45
45
|
|
|
46
46
|
# 创建连接器
|
|
@@ -51,6 +51,8 @@ class AioHttpDownloader(DownloaderBase):
|
|
|
51
51
|
ttl_dns_cache=300,
|
|
52
52
|
keepalive_timeout=15,
|
|
53
53
|
force_close=False,
|
|
54
|
+
use_dns_cache=True, # 启用DNS缓存
|
|
55
|
+
family=0, # 允许IPv4和IPv6
|
|
54
56
|
)
|
|
55
57
|
|
|
56
58
|
# 超时控制
|
crawlo/extension/__init__.py
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
from typing import Any
|
|
2
2
|
from crawlo.exceptions import NotConfigured
|
|
3
|
-
from crawlo.utils.log import
|
|
3
|
+
from crawlo.utils.log import get_logger
|
|
4
4
|
|
|
5
|
-
#
|
|
6
|
-
|
|
5
|
+
# 延迟获取logger,确保在日志系统配置之后获取
|
|
6
|
+
_logger = None
|
|
7
|
+
|
|
8
|
+
def logger():
|
|
9
|
+
"""延迟获取logger实例,确保在日志系统配置之后获取"""
|
|
10
|
+
global _logger
|
|
11
|
+
if _logger is None:
|
|
12
|
+
_logger = get_logger(__name__)
|
|
13
|
+
return _logger
|
|
7
14
|
|
|
8
15
|
|
|
9
16
|
class CustomLoggerExtension:
|
|
@@ -14,8 +21,17 @@ class CustomLoggerExtension:
|
|
|
14
21
|
|
|
15
22
|
def __init__(self, settings: Any):
|
|
16
23
|
self.settings = settings
|
|
17
|
-
#
|
|
18
|
-
|
|
24
|
+
# 使用新的日志系统,但要简化配置传递
|
|
25
|
+
try:
|
|
26
|
+
from crawlo.logging import configure_logging
|
|
27
|
+
# 直接传递settings对象,让日志系统内部处理
|
|
28
|
+
configure_logging(settings)
|
|
29
|
+
except Exception as e:
|
|
30
|
+
# 如果日志系统配置失败,不应该阻止扩展加载
|
|
31
|
+
# 使用基本日志输出错误信息
|
|
32
|
+
import logging
|
|
33
|
+
logging.getLogger(__name__).warning(f"Failed to configure logging system: {e}")
|
|
34
|
+
# 不抛出异常,让扩展继续加载
|
|
19
35
|
|
|
20
36
|
@classmethod
|
|
21
37
|
def create_instance(cls, crawler: Any, *args: Any, **kwargs: Any) -> 'CustomLoggerExtension':
|
|
@@ -34,9 +50,9 @@ class CustomLoggerExtension:
|
|
|
34
50
|
return cls(crawler.settings)
|
|
35
51
|
|
|
36
52
|
def spider_opened(self, spider: Any) -> None:
|
|
37
|
-
|
|
53
|
+
logger_instance = logger()
|
|
38
54
|
try:
|
|
39
|
-
|
|
55
|
+
logger_instance.info(
|
|
40
56
|
f"CustomLoggerExtension: Logging initialized. "
|
|
41
57
|
f"LOG_FILE={self.settings.get('LOG_FILE')}, "
|
|
42
58
|
f"LOG_LEVEL={self.settings.get('LOG_LEVEL')}"
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawlo组件工厂系统
|
|
5
|
+
==================
|
|
6
|
+
|
|
7
|
+
提供统一的组件创建和依赖注入机制
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .registry import ComponentRegistry, get_component_registry
|
|
11
|
+
from .base import ComponentFactory, ComponentSpec
|
|
12
|
+
from .crawler import CrawlerComponentFactory
|
|
13
|
+
|
|
14
|
+
# 公共接口
|
|
15
|
+
register_component = get_component_registry().register
|
|
16
|
+
get_component = get_component_registry().get
|
|
17
|
+
create_component = get_component_registry().create
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
'ComponentRegistry',
|
|
21
|
+
'ComponentFactory',
|
|
22
|
+
'ComponentSpec',
|
|
23
|
+
'CrawlerComponentFactory',
|
|
24
|
+
'get_component_registry',
|
|
25
|
+
'register_component',
|
|
26
|
+
'get_component',
|
|
27
|
+
'create_component'
|
|
28
|
+
]
|
crawlo/factories/base.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
组件工厂基类和规范
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import Type, Any, Dict, Optional, Callable
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class ComponentSpec:
|
|
14
|
+
"""组件规范 - 定义如何创建组件"""
|
|
15
|
+
|
|
16
|
+
name: str
|
|
17
|
+
component_type: Type
|
|
18
|
+
factory_func: Callable[..., Any]
|
|
19
|
+
dependencies: list = None
|
|
20
|
+
singleton: bool = False
|
|
21
|
+
config_key: str = None
|
|
22
|
+
|
|
23
|
+
def __post_init__(self):
|
|
24
|
+
if self.dependencies is None:
|
|
25
|
+
self.dependencies = []
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ComponentFactory(ABC):
|
|
29
|
+
"""组件工厂基类"""
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def create(self, spec: ComponentSpec, **kwargs) -> Any:
|
|
33
|
+
"""创建组件实例"""
|
|
34
|
+
pass
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
def supports(self, component_type: Type) -> bool:
|
|
38
|
+
"""检查是否支持指定类型的组件"""
|
|
39
|
+
pass
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class DefaultComponentFactory(ComponentFactory):
|
|
43
|
+
"""默认组件工厂实现"""
|
|
44
|
+
|
|
45
|
+
def __init__(self):
|
|
46
|
+
self._instances: Dict[str, Any] = {}
|
|
47
|
+
|
|
48
|
+
def create(self, spec: ComponentSpec, **kwargs) -> Any:
|
|
49
|
+
"""创建组件实例"""
|
|
50
|
+
# 单例模式检查
|
|
51
|
+
if spec.singleton and spec.name in self._instances:
|
|
52
|
+
return self._instances[spec.name]
|
|
53
|
+
|
|
54
|
+
# 调用工厂函数创建实例
|
|
55
|
+
instance = spec.factory_func(**kwargs)
|
|
56
|
+
|
|
57
|
+
# 保存单例实例
|
|
58
|
+
if spec.singleton:
|
|
59
|
+
self._instances[spec.name] = instance
|
|
60
|
+
|
|
61
|
+
return instance
|
|
62
|
+
|
|
63
|
+
def supports(self, component_type: Type) -> bool:
|
|
64
|
+
"""支持所有类型"""
|
|
65
|
+
return True
|
|
66
|
+
|
|
67
|
+
def clear_singletons(self):
|
|
68
|
+
"""清除单例实例(测试用)"""
|
|
69
|
+
self._instances.clear()
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawler组件工厂 - 专门用于创建Crawler相关组件
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, Type
|
|
8
|
+
|
|
9
|
+
from .base import ComponentFactory, ComponentSpec
|
|
10
|
+
from .registry import get_component_registry
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CrawlerComponentFactory(ComponentFactory):
|
|
14
|
+
"""Crawler组件工厂"""
|
|
15
|
+
|
|
16
|
+
def create(self, spec: ComponentSpec, **kwargs) -> Any:
|
|
17
|
+
"""创建Crawler相关组件"""
|
|
18
|
+
# 检查是否需要crawler依赖
|
|
19
|
+
if 'crawler' in spec.dependencies and 'crawler' not in kwargs:
|
|
20
|
+
raise ValueError(f"Crawler instance required for component {spec.name}")
|
|
21
|
+
|
|
22
|
+
return spec.factory_func(**kwargs)
|
|
23
|
+
|
|
24
|
+
def supports(self, component_type: Type) -> bool:
|
|
25
|
+
"""检查是否支持指定类型"""
|
|
26
|
+
# 这里可以根据需要定义支持的组件类型
|
|
27
|
+
supported_types = [
|
|
28
|
+
'Engine', 'Scheduler', 'StatsCollector',
|
|
29
|
+
'Subscriber', 'ExtensionManager'
|
|
30
|
+
]
|
|
31
|
+
return component_type.__name__ in supported_types
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def register_crawler_components():
|
|
35
|
+
"""注册Crawler相关组件"""
|
|
36
|
+
registry = get_component_registry()
|
|
37
|
+
|
|
38
|
+
# 注册工厂
|
|
39
|
+
registry.register_factory(CrawlerComponentFactory())
|
|
40
|
+
|
|
41
|
+
# 注册组件规范
|
|
42
|
+
|
|
43
|
+
# Engine组件
|
|
44
|
+
def create_engine(crawler, **kwargs):
|
|
45
|
+
from crawlo.core.engine import Engine
|
|
46
|
+
return Engine(crawler)
|
|
47
|
+
|
|
48
|
+
registry.register(ComponentSpec(
|
|
49
|
+
name='engine',
|
|
50
|
+
component_type=type('Engine', (), {}),
|
|
51
|
+
factory_func=create_engine,
|
|
52
|
+
dependencies=['crawler']
|
|
53
|
+
))
|
|
54
|
+
|
|
55
|
+
# Scheduler组件
|
|
56
|
+
def create_scheduler(crawler, **kwargs):
|
|
57
|
+
from crawlo.core.scheduler import Scheduler
|
|
58
|
+
return Scheduler.create_instance(crawler)
|
|
59
|
+
|
|
60
|
+
registry.register(ComponentSpec(
|
|
61
|
+
name='scheduler',
|
|
62
|
+
component_type=type('Scheduler', (), {}),
|
|
63
|
+
factory_func=create_scheduler,
|
|
64
|
+
dependencies=['crawler']
|
|
65
|
+
))
|
|
66
|
+
|
|
67
|
+
# StatsCollector组件
|
|
68
|
+
def create_stats(crawler, **kwargs):
|
|
69
|
+
from crawlo.stats_collector import StatsCollector
|
|
70
|
+
return StatsCollector(crawler)
|
|
71
|
+
|
|
72
|
+
registry.register(ComponentSpec(
|
|
73
|
+
name='stats',
|
|
74
|
+
component_type=type('StatsCollector', (), {}),
|
|
75
|
+
factory_func=create_stats,
|
|
76
|
+
dependencies=['crawler']
|
|
77
|
+
))
|
|
78
|
+
|
|
79
|
+
# Subscriber组件
|
|
80
|
+
def create_subscriber(**kwargs):
|
|
81
|
+
from crawlo.subscriber import Subscriber
|
|
82
|
+
return Subscriber()
|
|
83
|
+
|
|
84
|
+
registry.register(ComponentSpec(
|
|
85
|
+
name='subscriber',
|
|
86
|
+
component_type=type('Subscriber', (), {}),
|
|
87
|
+
factory_func=create_subscriber
|
|
88
|
+
))
|
|
89
|
+
|
|
90
|
+
# ExtensionManager组件
|
|
91
|
+
def create_extension_manager(crawler, **kwargs):
|
|
92
|
+
from crawlo.extension import ExtensionManager
|
|
93
|
+
return ExtensionManager.create_instance(crawler)
|
|
94
|
+
|
|
95
|
+
registry.register(ComponentSpec(
|
|
96
|
+
name='extension_manager',
|
|
97
|
+
component_type=type('ExtensionManager', (), {}),
|
|
98
|
+
factory_func=create_extension_manager,
|
|
99
|
+
dependencies=['crawler']
|
|
100
|
+
))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# 自动注册
|
|
104
|
+
register_crawler_components()
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
组件注册表 - 管理所有组件的注册和创建
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import threading
|
|
8
|
+
from typing import Dict, List, Type, Any, Optional
|
|
9
|
+
|
|
10
|
+
from .base import ComponentFactory, ComponentSpec, DefaultComponentFactory
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ComponentRegistry:
|
|
14
|
+
"""
|
|
15
|
+
组件注册表
|
|
16
|
+
|
|
17
|
+
职责:
|
|
18
|
+
1. 管理组件规范的注册
|
|
19
|
+
2. 根据类型查找合适的工厂
|
|
20
|
+
3. 处理依赖关系
|
|
21
|
+
4. 创建组件实例
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
def __init__(self):
|
|
25
|
+
self._specs: Dict[str, ComponentSpec] = {}
|
|
26
|
+
self._factories: List[ComponentFactory] = []
|
|
27
|
+
self._default_factory = DefaultComponentFactory()
|
|
28
|
+
self._lock = threading.RLock()
|
|
29
|
+
|
|
30
|
+
def register(self, spec: ComponentSpec):
|
|
31
|
+
"""注册组件规范"""
|
|
32
|
+
with self._lock:
|
|
33
|
+
self._specs[spec.name] = spec
|
|
34
|
+
|
|
35
|
+
def register_factory(self, factory: ComponentFactory):
|
|
36
|
+
"""注册组件工厂"""
|
|
37
|
+
with self._lock:
|
|
38
|
+
self._factories.append(factory)
|
|
39
|
+
|
|
40
|
+
def get_spec(self, name: str) -> Optional[ComponentSpec]:
|
|
41
|
+
"""获取组件规范"""
|
|
42
|
+
with self._lock:
|
|
43
|
+
return self._specs.get(name)
|
|
44
|
+
|
|
45
|
+
def get_factory(self, component_type: Type) -> ComponentFactory:
|
|
46
|
+
"""获取支持指定类型的工厂"""
|
|
47
|
+
with self._lock:
|
|
48
|
+
for factory in self._factories:
|
|
49
|
+
if factory.supports(component_type):
|
|
50
|
+
return factory
|
|
51
|
+
return self._default_factory
|
|
52
|
+
|
|
53
|
+
def create(self, name: str, **kwargs) -> Any:
|
|
54
|
+
"""创建组件实例"""
|
|
55
|
+
spec = self.get_spec(name)
|
|
56
|
+
if not spec:
|
|
57
|
+
raise ValueError(f"Component spec '{name}' not found")
|
|
58
|
+
|
|
59
|
+
factory = self.get_factory(spec.component_type)
|
|
60
|
+
return factory.create(spec, **kwargs)
|
|
61
|
+
|
|
62
|
+
def get(self, name: str, **kwargs) -> Any:
|
|
63
|
+
"""获取组件实例(create的别名)"""
|
|
64
|
+
return self.create(name, **kwargs)
|
|
65
|
+
|
|
66
|
+
def list_components(self) -> List[str]:
|
|
67
|
+
"""列出所有已注册的组件"""
|
|
68
|
+
with self._lock:
|
|
69
|
+
return list(self._specs.keys())
|
|
70
|
+
|
|
71
|
+
def clear(self):
|
|
72
|
+
"""清空注册表"""
|
|
73
|
+
with self._lock:
|
|
74
|
+
self._specs.clear()
|
|
75
|
+
self._factories.clear()
|
|
76
|
+
self._default_factory.clear_singletons()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# 全局组件注册表
|
|
80
|
+
_global_registry = ComponentRegistry()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_component_registry() -> ComponentRegistry:
|
|
84
|
+
"""获取全局组件注册表"""
|
|
85
|
+
return _global_registry
|
|
@@ -206,9 +206,32 @@ class AioRedisFilter(BaseFilter):
|
|
|
206
206
|
self.logger.error(f"添加指纹失败: {fp[:20]}... - {e}")
|
|
207
207
|
return False
|
|
208
208
|
|
|
209
|
-
|
|
209
|
+
def __contains__(self, fp: str) -> bool:
|
|
210
210
|
"""
|
|
211
|
-
检查指纹是否存在于Redis
|
|
211
|
+
检查指纹是否存在于Redis集合中(同步方法)
|
|
212
|
+
|
|
213
|
+
注意:Python的魔术方法__contains__不能是异步的,
|
|
214
|
+
所以这个方法提供同步接口,仅用于基本的存在性检查。
|
|
215
|
+
对于需要异步检查的场景,请使用 contains_async() 方法。
|
|
216
|
+
|
|
217
|
+
:param fp: 请求指纹字符串
|
|
218
|
+
:return: 是否存在
|
|
219
|
+
"""
|
|
220
|
+
# 由于__contains__不能是异步的,我们只能提供一个基本的同步检查
|
|
221
|
+
# 如果Redis客户端未初始化,返回False
|
|
222
|
+
if self.redis is None:
|
|
223
|
+
return False
|
|
224
|
+
|
|
225
|
+
# 对于同步场景,我们无法进行真正的Redis查询
|
|
226
|
+
# 所以返回False,避免阻塞调用
|
|
227
|
+
# 真正的异步检查应该使用 contains_async() 方法
|
|
228
|
+
return False
|
|
229
|
+
|
|
230
|
+
async def contains_async(self, fp: str) -> bool:
|
|
231
|
+
"""
|
|
232
|
+
异步检查指纹是否存在于Redis集合中
|
|
233
|
+
|
|
234
|
+
这是真正的异步检查方法,应该优先使用这个方法而不是__contains__
|
|
212
235
|
|
|
213
236
|
:param fp: 请求指纹字符串
|
|
214
237
|
:return: 是否存在
|
crawlo/framework.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawlo框架统一入口
|
|
5
|
+
================
|
|
6
|
+
|
|
7
|
+
提供简洁、一致的API接口,隐藏内部复杂性
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from typing import Type, Optional, List, Union
|
|
13
|
+
|
|
14
|
+
from .crawler import ModernCrawler, CrawlerProcess
|
|
15
|
+
from .initialization import initialize_framework
|
|
16
|
+
from .logging import get_logger
|
|
17
|
+
from .utils.env_config import get_version
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CrawloFramework:
|
|
21
|
+
"""
|
|
22
|
+
Crawlo框架门面类
|
|
23
|
+
|
|
24
|
+
提供统一的框架入口点,简化使用复杂度
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, settings=None, **kwargs):
|
|
28
|
+
"""
|
|
29
|
+
初始化框架
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
settings: 配置对象
|
|
33
|
+
**kwargs: 额外配置参数
|
|
34
|
+
"""
|
|
35
|
+
# 合并配置
|
|
36
|
+
config = {}
|
|
37
|
+
if settings:
|
|
38
|
+
if hasattr(settings, '__dict__'):
|
|
39
|
+
config.update(settings.__dict__)
|
|
40
|
+
elif isinstance(settings, dict):
|
|
41
|
+
config.update(settings)
|
|
42
|
+
config.update(kwargs)
|
|
43
|
+
|
|
44
|
+
# 如果没有提供配置,尝试自动加载项目配置
|
|
45
|
+
if not config:
|
|
46
|
+
config = self._load_project_config()
|
|
47
|
+
|
|
48
|
+
# 初始化框架
|
|
49
|
+
self._settings = initialize_framework(config)
|
|
50
|
+
self._logger = get_logger('crawlo.framework')
|
|
51
|
+
|
|
52
|
+
# 获取版本号
|
|
53
|
+
version = get_version()
|
|
54
|
+
|
|
55
|
+
# 创建进程管理器
|
|
56
|
+
self._process = CrawlerProcess(self._settings)
|
|
57
|
+
|
|
58
|
+
self._logger.info(f"Crawlo Framework Started {version}")
|
|
59
|
+
|
|
60
|
+
# 获取运行模式并记录日志
|
|
61
|
+
run_mode = self._settings.get('RUN_MODE', 'unknown')
|
|
62
|
+
self._logger.info(f"Run mode: {run_mode}")
|
|
63
|
+
|
|
64
|
+
# 记录项目名称
|
|
65
|
+
project_name = self._settings.get('PROJECT_NAME', 'unknown')
|
|
66
|
+
self._logger.info(f"Project: {project_name}")
|
|
67
|
+
|
|
68
|
+
def _load_project_config(self):
|
|
69
|
+
"""
|
|
70
|
+
自动加载项目配置
|
|
71
|
+
"""
|
|
72
|
+
try:
|
|
73
|
+
# 查找项目根目录
|
|
74
|
+
project_root = self._find_project_root()
|
|
75
|
+
if not project_root:
|
|
76
|
+
print("警告: 未找到项目根目录,使用默认配置")
|
|
77
|
+
return {}
|
|
78
|
+
|
|
79
|
+
# 添加项目根目录到Python路径
|
|
80
|
+
if project_root not in sys.path:
|
|
81
|
+
sys.path.insert(0, project_root)
|
|
82
|
+
|
|
83
|
+
# 读取crawlo.cfg配置文件
|
|
84
|
+
cfg_file = os.path.join(project_root, "crawlo.cfg")
|
|
85
|
+
if not os.path.exists(cfg_file):
|
|
86
|
+
print(f"警告: 未找到配置文件 {cfg_file},使用默认配置")
|
|
87
|
+
return {}
|
|
88
|
+
|
|
89
|
+
import configparser
|
|
90
|
+
config_parser = configparser.ConfigParser()
|
|
91
|
+
config_parser.read(cfg_file, encoding="utf-8")
|
|
92
|
+
|
|
93
|
+
if not config_parser.has_section("settings") or not config_parser.has_option("settings", "default"):
|
|
94
|
+
print("警告: 配置文件缺少 [settings] 部分或 'default' 选项,使用默认配置")
|
|
95
|
+
return {}
|
|
96
|
+
|
|
97
|
+
# 获取settings模块路径
|
|
98
|
+
settings_module_path = config_parser.get("settings", "default")
|
|
99
|
+
project_package = settings_module_path.split(".")[0]
|
|
100
|
+
|
|
101
|
+
# 导入项目配置模块
|
|
102
|
+
import importlib
|
|
103
|
+
settings_module = importlib.import_module(settings_module_path)
|
|
104
|
+
|
|
105
|
+
# 创建配置字典
|
|
106
|
+
project_config = {}
|
|
107
|
+
for key in dir(settings_module):
|
|
108
|
+
if key.isupper():
|
|
109
|
+
project_config[key] = getattr(settings_module, key)
|
|
110
|
+
|
|
111
|
+
# print(f"已加载项目配置: {settings_module_path}")
|
|
112
|
+
return project_config
|
|
113
|
+
|
|
114
|
+
except Exception as e:
|
|
115
|
+
print(f"加载项目配置时出错: {e}")
|
|
116
|
+
return {}
|
|
117
|
+
|
|
118
|
+
def _find_project_root(self):
|
|
119
|
+
"""
|
|
120
|
+
查找项目根目录(包含crawlo.cfg的目录)
|
|
121
|
+
"""
|
|
122
|
+
current_path = os.getcwd()
|
|
123
|
+
|
|
124
|
+
# 向上查找直到找到crawlo.cfg
|
|
125
|
+
checked_paths = set()
|
|
126
|
+
path = current_path
|
|
127
|
+
|
|
128
|
+
while path not in checked_paths:
|
|
129
|
+
checked_paths.add(path)
|
|
130
|
+
|
|
131
|
+
# 检查crawlo.cfg
|
|
132
|
+
cfg_file = os.path.join(path, "crawlo.cfg")
|
|
133
|
+
if os.path.exists(cfg_file):
|
|
134
|
+
return path
|
|
135
|
+
|
|
136
|
+
# 向上一级目录
|
|
137
|
+
parent = os.path.dirname(path)
|
|
138
|
+
if parent == path:
|
|
139
|
+
break
|
|
140
|
+
path = parent
|
|
141
|
+
|
|
142
|
+
return None
|
|
143
|
+
|
|
144
|
+
@property
|
|
145
|
+
def settings(self):
|
|
146
|
+
"""获取配置"""
|
|
147
|
+
return self._settings
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def logger(self):
|
|
151
|
+
"""获取框架日志器"""
|
|
152
|
+
return self._logger
|
|
153
|
+
|
|
154
|
+
async def run(self, spider_cls_or_name, settings=None):
|
|
155
|
+
"""
|
|
156
|
+
运行单个爬虫
|
|
157
|
+
|
|
158
|
+
Args:
|
|
159
|
+
spider_cls_or_name: Spider类或名称
|
|
160
|
+
settings: 额外配置
|
|
161
|
+
|
|
162
|
+
Returns:
|
|
163
|
+
Crawler实例
|
|
164
|
+
"""
|
|
165
|
+
# 记录启动的爬虫名称
|
|
166
|
+
if isinstance(spider_cls_or_name, str):
|
|
167
|
+
spider_name = spider_cls_or_name
|
|
168
|
+
else:
|
|
169
|
+
spider_name = getattr(spider_cls_or_name, 'name', spider_cls_or_name.__name__)
|
|
170
|
+
|
|
171
|
+
self._logger.info(f"Starting spider: {spider_name}")
|
|
172
|
+
|
|
173
|
+
return await self._process.crawl(spider_cls_or_name, settings)
|
|
174
|
+
|
|
175
|
+
async def run_multiple(self, spider_classes_or_names: List[Union[Type, str]],
|
|
176
|
+
settings=None):
|
|
177
|
+
"""
|
|
178
|
+
运行多个爬虫
|
|
179
|
+
|
|
180
|
+
Args:
|
|
181
|
+
spider_classes_or_names: Spider类或名称列表
|
|
182
|
+
settings: 额外配置
|
|
183
|
+
|
|
184
|
+
Returns:
|
|
185
|
+
结果列表
|
|
186
|
+
"""
|
|
187
|
+
# 记录启动的爬虫名称
|
|
188
|
+
spider_names = []
|
|
189
|
+
for spider_cls_or_name in spider_classes_or_names:
|
|
190
|
+
if isinstance(spider_cls_or_name, str):
|
|
191
|
+
spider_names.append(spider_cls_or_name)
|
|
192
|
+
else:
|
|
193
|
+
spider_names.append(getattr(spider_cls_or_name, 'name', spider_cls_or_name.__name__))
|
|
194
|
+
|
|
195
|
+
self._logger.info(f"Starting spiders: {', '.join(spider_names)}")
|
|
196
|
+
|
|
197
|
+
return await self._process.crawl_multiple(spider_classes_or_names, settings)
|
|
198
|
+
|
|
199
|
+
def create_crawler(self, spider_cls: Type, settings=None) -> ModernCrawler:
|
|
200
|
+
"""
|
|
201
|
+
创建Crawler实例
|
|
202
|
+
|
|
203
|
+
Args:
|
|
204
|
+
spider_cls: Spider类
|
|
205
|
+
settings: 额外配置
|
|
206
|
+
|
|
207
|
+
Returns:
|
|
208
|
+
ModernCrawler实例
|
|
209
|
+
"""
|
|
210
|
+
merged_settings = self._merge_settings(settings)
|
|
211
|
+
return ModernCrawler(spider_cls, merged_settings)
|
|
212
|
+
|
|
213
|
+
def _merge_settings(self, additional_settings):
|
|
214
|
+
"""合并配置"""
|
|
215
|
+
if not additional_settings:
|
|
216
|
+
return self._settings
|
|
217
|
+
|
|
218
|
+
from .settings.setting_manager import SettingManager
|
|
219
|
+
merged = SettingManager()
|
|
220
|
+
|
|
221
|
+
# 复制基础配置
|
|
222
|
+
if self._settings:
|
|
223
|
+
merged.update_attributes(self._settings.__dict__)
|
|
224
|
+
|
|
225
|
+
# 应用额外配置
|
|
226
|
+
if isinstance(additional_settings, dict):
|
|
227
|
+
merged.update_attributes(additional_settings)
|
|
228
|
+
elif hasattr(additional_settings, '__dict__'):
|
|
229
|
+
merged.update_attributes(additional_settings.__dict__)
|
|
230
|
+
|
|
231
|
+
return merged
|
|
232
|
+
|
|
233
|
+
def get_metrics(self) -> dict:
|
|
234
|
+
"""获取框架指标"""
|
|
235
|
+
return self._process.get_metrics()
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# 全局框架实例
|
|
239
|
+
_global_framework: Optional[CrawloFramework] = None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def get_framework(settings=None, **kwargs) -> CrawloFramework:
|
|
243
|
+
"""
|
|
244
|
+
获取全局框架实例(单例模式)
|
|
245
|
+
|
|
246
|
+
Args:
|
|
247
|
+
settings: 配置对象
|
|
248
|
+
**kwargs: 额外配置参数
|
|
249
|
+
|
|
250
|
+
Returns:
|
|
251
|
+
CrawloFramework实例
|
|
252
|
+
"""
|
|
253
|
+
global _global_framework
|
|
254
|
+
|
|
255
|
+
if _global_framework is None:
|
|
256
|
+
_global_framework = CrawloFramework(settings, **kwargs)
|
|
257
|
+
|
|
258
|
+
return _global_framework
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def reset_framework():
|
|
262
|
+
"""重置全局框架实例(主要用于测试)"""
|
|
263
|
+
global _global_framework
|
|
264
|
+
_global_framework = None
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
# 便捷函数
|
|
268
|
+
async def run_spider(spider_cls_or_name, settings=None, **kwargs):
|
|
269
|
+
"""运行单个爬虫的便捷函数"""
|
|
270
|
+
framework = get_framework(settings, **kwargs)
|
|
271
|
+
return await framework.run(spider_cls_or_name)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def run_spiders(spider_classes_or_names: List[Union[Type, str]],
|
|
275
|
+
settings=None, **kwargs):
|
|
276
|
+
"""运行多个爬虫的便捷函数"""
|
|
277
|
+
framework = get_framework(settings, **kwargs)
|
|
278
|
+
return await framework.run_multiple(spider_classes_or_names)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def create_crawler(spider_cls: Type, settings=None, **kwargs) -> ModernCrawler:
|
|
282
|
+
"""创建Crawler的便捷函数"""
|
|
283
|
+
framework = get_framework(settings, **kwargs)
|
|
284
|
+
return framework.create_crawler(spider_cls)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
# 配置相关便捷函数
|
|
288
|
+
def configure_framework(settings=None, **kwargs):
|
|
289
|
+
"""配置框架的便捷函数"""
|
|
290
|
+
if settings or kwargs:
|
|
291
|
+
reset_framework() # 重置以应用新配置
|
|
292
|
+
return get_framework(settings, **kwargs)
|