crawlo 1.1.3__py3-none-any.whl → 1.1.5__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 +28 -1
- crawlo/__version__.py +1 -1
- crawlo/cleaners/__init__.py +61 -0
- crawlo/cleaners/data_formatter.py +226 -0
- crawlo/cleaners/encoding_converter.py +126 -0
- crawlo/cleaners/text_cleaner.py +233 -0
- crawlo/commands/startproject.py +117 -13
- crawlo/config.py +30 -0
- crawlo/config_validator.py +253 -0
- crawlo/core/engine.py +185 -11
- crawlo/core/scheduler.py +49 -78
- crawlo/crawler.py +6 -6
- crawlo/downloader/__init__.py +24 -0
- crawlo/downloader/aiohttp_downloader.py +8 -0
- crawlo/downloader/cffi_downloader.py +5 -0
- crawlo/downloader/hybrid_downloader.py +214 -0
- crawlo/downloader/playwright_downloader.py +403 -0
- crawlo/downloader/selenium_downloader.py +473 -0
- crawlo/extension/__init__.py +17 -10
- crawlo/extension/health_check.py +142 -0
- crawlo/extension/log_interval.py +27 -18
- crawlo/extension/log_stats.py +62 -24
- crawlo/extension/logging_extension.py +18 -9
- crawlo/extension/memory_monitor.py +105 -0
- crawlo/extension/performance_profiler.py +134 -0
- crawlo/extension/request_recorder.py +108 -0
- crawlo/filters/aioredis_filter.py +50 -12
- crawlo/middleware/proxy.py +26 -2
- crawlo/mode_manager.py +24 -19
- crawlo/network/request.py +30 -3
- crawlo/network/response.py +114 -25
- crawlo/pipelines/mongo_pipeline.py +81 -66
- crawlo/pipelines/mysql_pipeline.py +165 -43
- crawlo/pipelines/redis_dedup_pipeline.py +7 -3
- crawlo/queue/queue_manager.py +15 -2
- crawlo/queue/redis_priority_queue.py +144 -76
- crawlo/settings/default_settings.py +93 -121
- crawlo/subscriber.py +62 -37
- crawlo/templates/project/items.py.tmpl +1 -1
- crawlo/templates/project/middlewares.py.tmpl +73 -49
- crawlo/templates/project/pipelines.py.tmpl +51 -295
- crawlo/templates/project/settings.py.tmpl +93 -17
- crawlo/templates/project/settings_distributed.py.tmpl +120 -0
- crawlo/templates/project/settings_gentle.py.tmpl +95 -0
- crawlo/templates/project/settings_high_performance.py.tmpl +152 -0
- crawlo/templates/project/settings_simple.py.tmpl +69 -0
- crawlo/templates/spider/spider.py.tmpl +2 -38
- crawlo/tools/__init__.py +183 -0
- crawlo/tools/anti_crawler.py +269 -0
- crawlo/tools/authenticated_proxy.py +241 -0
- crawlo/tools/data_validator.py +181 -0
- crawlo/tools/date_tools.py +36 -0
- crawlo/tools/distributed_coordinator.py +387 -0
- crawlo/tools/retry_mechanism.py +221 -0
- crawlo/tools/scenario_adapter.py +263 -0
- crawlo/utils/__init__.py +29 -1
- crawlo/utils/batch_processor.py +261 -0
- crawlo/utils/date_tools.py +58 -1
- crawlo/utils/enhanced_error_handler.py +360 -0
- crawlo/utils/env_config.py +106 -0
- crawlo/utils/error_handler.py +126 -0
- crawlo/utils/performance_monitor.py +285 -0
- crawlo/utils/redis_connection_pool.py +335 -0
- crawlo/utils/redis_key_validator.py +200 -0
- crawlo-1.1.5.dist-info/METADATA +401 -0
- crawlo-1.1.5.dist-info/RECORD +185 -0
- tests/advanced_tools_example.py +276 -0
- tests/authenticated_proxy_example.py +237 -0
- tests/cleaners_example.py +161 -0
- tests/config_validation_demo.py +103 -0
- tests/date_tools_example.py +181 -0
- tests/dynamic_loading_example.py +524 -0
- tests/dynamic_loading_test.py +105 -0
- tests/env_config_example.py +134 -0
- tests/error_handling_example.py +172 -0
- tests/redis_key_validation_demo.py +131 -0
- tests/response_improvements_example.py +145 -0
- tests/test_advanced_tools.py +149 -0
- tests/test_all_redis_key_configs.py +146 -0
- tests/test_authenticated_proxy.py +142 -0
- tests/test_cleaners.py +55 -0
- tests/test_comprehensive.py +147 -0
- tests/test_config_validator.py +194 -0
- tests/test_date_tools.py +124 -0
- tests/test_dynamic_downloaders_proxy.py +125 -0
- tests/test_dynamic_proxy.py +93 -0
- tests/test_dynamic_proxy_config.py +147 -0
- tests/test_dynamic_proxy_real.py +110 -0
- tests/test_edge_cases.py +304 -0
- tests/test_enhanced_error_handler.py +271 -0
- tests/test_env_config.py +122 -0
- tests/test_error_handler_compatibility.py +113 -0
- tests/test_framework_env_usage.py +104 -0
- tests/test_integration.py +357 -0
- tests/test_item_dedup_redis_key.py +123 -0
- tests/test_parsel.py +30 -0
- tests/test_performance.py +328 -0
- tests/test_queue_manager_redis_key.py +177 -0
- tests/test_redis_connection_pool.py +295 -0
- tests/test_redis_key_naming.py +182 -0
- tests/test_redis_key_validator.py +124 -0
- tests/test_response_improvements.py +153 -0
- tests/test_simple_response.py +62 -0
- tests/test_telecom_spider_redis_key.py +206 -0
- tests/test_template_content.py +88 -0
- tests/test_template_redis_key.py +135 -0
- tests/test_tools.py +154 -0
- tests/tools_example.py +258 -0
- crawlo/core/enhanced_engine.py +0 -190
- crawlo-1.1.3.dist-info/METADATA +0 -635
- crawlo-1.1.3.dist-info/RECORD +0 -113
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/WHEEL +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/top_level.txt +0 -0
- {examples → tests}/controlled_spider_example.py +0 -0
|
@@ -1,139 +1,78 @@
|
|
|
1
1
|
#!/usr/bin/python
|
|
2
|
-
# -*- coding:
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
3
|
"""
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
==================================
|
|
7
|
-
说明:
|
|
8
|
-
- 所有配置项均已按功能模块分类。
|
|
9
|
-
- 支持通过环境变量覆盖部分敏感配置(如 Redis、MySQL 密码等)。
|
|
10
|
-
- 可根据需求启用/禁用组件(如 MySQL、Redis、Proxy 等)。
|
|
4
|
+
默认配置文件
|
|
5
|
+
包含 Crawlo 框架的所有默认设置项
|
|
11
6
|
"""
|
|
12
7
|
import os
|
|
13
8
|
|
|
14
|
-
#
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
# ==============================
|
|
18
|
-
|
|
19
|
-
#
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
#
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
#
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
#
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
#
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
#
|
|
37
|
-
|
|
38
|
-
RANDOM_RANGE =
|
|
39
|
-
RANDOMNESS = True # 是否启用随机延迟
|
|
40
|
-
|
|
41
|
-
# 重试策略
|
|
42
|
-
MAX_RETRY_TIMES = 3 # 最大重试次数
|
|
43
|
-
RETRY_PRIORITY = -1 # 重试请求的优先级调整
|
|
44
|
-
RETRY_HTTP_CODES = [408, 429, 500, 502, 503, 504, 522, 524] # 触发重试的状态码
|
|
45
|
-
IGNORE_HTTP_CODES = [403, 404] # 直接标记成功、不重试的状态码
|
|
46
|
-
ALLOWED_CODES = [] # 允许的状态码(空表示不限制)
|
|
47
|
-
|
|
48
|
-
# 连接与响应大小限制
|
|
49
|
-
CONNECTION_POOL_LIMIT = 50 # 最大并发连接数(连接池大小)
|
|
50
|
-
CONNECTION_POOL_LIMIT_PER_HOST = 20 # 每个主机的连接池大小
|
|
51
|
-
DOWNLOAD_MAXSIZE = 10 * 1024 * 1024 # 最大响应体大小(10MB)
|
|
52
|
-
DOWNLOAD_WARN_SIZE = 1024 * 1024 # 响应体警告阈值(1MB)
|
|
53
|
-
DOWNLOAD_RETRY_TIMES = MAX_RETRY_TIMES # 下载器内部重试次数(复用全局)
|
|
54
|
-
|
|
55
|
-
# 下载统计配置
|
|
56
|
-
DOWNLOADER_STATS = True # 是否启用下载器统计功能
|
|
57
|
-
DOWNLOAD_STATS = True # 是否记录下载时间和大小统计
|
|
58
|
-
|
|
59
|
-
# ============================== 并发与调度 ==============================
|
|
60
|
-
|
|
61
|
-
CONCURRENCY = 8 # 单个爬虫的并发请求数
|
|
62
|
-
INTERVAL = 5 # 日志统计输出间隔(秒)
|
|
63
|
-
DEPTH_PRIORITY = 1 # 深度优先策略优先级
|
|
64
|
-
MAX_RUNNING_SPIDERS = 3 # 最大同时运行的爬虫数
|
|
65
|
-
|
|
66
|
-
# ============================== 队列配置 ==============================
|
|
67
|
-
|
|
68
|
-
# 🎯 运行模式选择:'standalone'(单机), 'distributed'(分布式), 'auto'(自动检测)
|
|
69
|
-
RUN_MODE = 'standalone' # 默认单机模式,简单易用
|
|
70
|
-
|
|
71
|
-
# 队列类型选择:'memory'(内存), 'redis'(分布式), 'auto'(自动选择)
|
|
72
|
-
QUEUE_TYPE = 'memory' # 默认内存队列,无需外部依赖
|
|
73
|
-
SCHEDULER_MAX_QUEUE_SIZE = 2000 # 调度器队列最大容量
|
|
74
|
-
SCHEDULER_QUEUE_NAME = 'crawlo:requests' # Redis 队列名称
|
|
75
|
-
QUEUE_MAX_RETRIES = 3 # 队列操作最大重试次数
|
|
76
|
-
QUEUE_TIMEOUT = 300 # 队列操作超时时间(秒)
|
|
77
|
-
|
|
78
|
-
# 大规模爬取优化配置
|
|
79
|
-
LARGE_SCALE_BATCH_SIZE = 1000 # 批处理大小
|
|
80
|
-
LARGE_SCALE_CHECKPOINT_INTERVAL = 5000 # 进度保存间隔
|
|
81
|
-
LARGE_SCALE_MAX_MEMORY_USAGE = 500 # 最大内存使用量(MB)
|
|
82
|
-
|
|
83
|
-
# ============================== 数据存储配置 ==============================
|
|
84
|
-
|
|
85
|
-
# --- MySQL 配置 ---
|
|
86
|
-
MYSQL_HOST = '127.0.0.1'
|
|
87
|
-
MYSQL_PORT = 3306
|
|
88
|
-
MYSQL_USER = 'root'
|
|
89
|
-
MYSQL_PASSWORD = '123456'
|
|
90
|
-
MYSQL_DB = 'crawl'
|
|
91
|
-
MYSQL_TABLE = 'crawlo'
|
|
92
|
-
MYSQL_BATCH_SIZE = 100 # 批量插入条数
|
|
93
|
-
|
|
94
|
-
# MySQL 连接池
|
|
95
|
-
MYSQL_FLUSH_INTERVAL = 5 # 缓存刷新间隔(秒)
|
|
96
|
-
MYSQL_POOL_MIN = 5
|
|
97
|
-
MYSQL_POOL_MAX = 20
|
|
98
|
-
MYSQL_ECHO = False # 是否打印 SQL 日志
|
|
99
|
-
|
|
100
|
-
# --- MongoDB 配置 ---
|
|
101
|
-
MONGO_URI = 'mongodb://user:password@host:27017'
|
|
102
|
-
MONGO_DATABASE = 'scrapy_data'
|
|
103
|
-
MONGO_COLLECTION = 'crawled_items'
|
|
104
|
-
MONGO_MAX_POOL_SIZE = 200
|
|
105
|
-
MONGO_MIN_POOL_SIZE = 20
|
|
106
|
-
|
|
107
|
-
# ============================== 去重过滤配置 ==============================
|
|
108
|
-
|
|
109
|
-
# 请求指纹存储目录(文件过滤器使用)
|
|
110
|
-
REQUEST_DIR = '.'
|
|
111
|
-
|
|
112
|
-
# 根据运行模式自动选择去重管道
|
|
113
|
-
# 单机模式默认使用内存去重管道
|
|
114
|
-
# 分布式模式默认使用Redis去重管道
|
|
115
|
-
if RUN_MODE == 'distributed':
|
|
116
|
-
# 分布式模式下默认使用Redis去重管道
|
|
117
|
-
DEFAULT_DEDUP_PIPELINE = 'crawlo.pipelines.RedisDedupPipeline'
|
|
118
|
-
else:
|
|
119
|
-
# 单机模式下默认使用内存去重管道
|
|
120
|
-
DEFAULT_DEDUP_PIPELINE = 'crawlo.pipelines.MemoryDedupPipeline'
|
|
9
|
+
# 添加环境变量配置工具导入
|
|
10
|
+
from crawlo.utils.env_config import get_redis_config, get_runtime_config
|
|
11
|
+
|
|
12
|
+
# ============================== 项目基础配置 ==============================
|
|
13
|
+
|
|
14
|
+
# 项目名称(用于日志、Redis Key 等标识)
|
|
15
|
+
PROJECT_NAME = get_runtime_config()['PROJECT_NAME']
|
|
16
|
+
|
|
17
|
+
# 框架版本
|
|
18
|
+
VERSION = 1.0
|
|
19
|
+
|
|
20
|
+
# 运行模式:standalone/distributed/auto
|
|
21
|
+
RUN_MODE = get_runtime_config()['CRAWLO_MODE']
|
|
22
|
+
|
|
23
|
+
# 并发数配置
|
|
24
|
+
CONCURRENCY = get_runtime_config()['CONCURRENCY']
|
|
25
|
+
|
|
26
|
+
# ============================== 爬虫核心配置 ==============================
|
|
27
|
+
|
|
28
|
+
# 请求延迟(秒)
|
|
29
|
+
DOWNLOAD_DELAY = 1
|
|
30
|
+
|
|
31
|
+
# 随机延迟配置
|
|
32
|
+
RANDOMNESS = False # 是否启用随机延迟
|
|
33
|
+
RANDOM_RANGE = [0.5, 1.5] # 随机延迟范围因子,实际延迟 = DOWNLOAD_DELAY * RANDOM_RANGE[0] 到 DOWNLOAD_DELAY * RANDOM_RANGE[1]
|
|
121
34
|
|
|
122
|
-
#
|
|
35
|
+
# 深度优先级(负数表示深度优先,正数表示广度优先)
|
|
36
|
+
DEPTH_PRIORITY = 1
|
|
37
|
+
|
|
38
|
+
# 调度器队列最大大小
|
|
39
|
+
SCHEDULER_MAX_QUEUE_SIZE = 1000
|
|
40
|
+
|
|
41
|
+
# 调度器队列名称(遵循统一命名规范)
|
|
42
|
+
SCHEDULER_QUEUE_NAME = f"crawlo:{PROJECT_NAME}:queue:requests"
|
|
43
|
+
|
|
44
|
+
# 队列类型:memory/redis/auto
|
|
45
|
+
QUEUE_TYPE = 'auto'
|
|
46
|
+
|
|
47
|
+
# 默认去重管道(根据运行模式自动选择)
|
|
48
|
+
DEFAULT_DEDUP_PIPELINE = 'crawlo.pipelines.redis_dedup_pipeline.RedisDedupPipeline'
|
|
49
|
+
|
|
50
|
+
# 请求去重过滤器
|
|
123
51
|
FILTER_CLASS = 'crawlo.filters.memory_filter.MemoryFilter'
|
|
124
52
|
# FILTER_CLASS = 'crawlo.filters.aioredis_filter.AioRedisFilter' # 分布式去重
|
|
125
53
|
|
|
126
54
|
# --- Redis 过滤器配置 ---
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
55
|
+
# 使用环境变量配置工具获取 Redis 配置
|
|
56
|
+
redis_config = get_redis_config()
|
|
57
|
+
REDIS_HOST = redis_config['REDIS_HOST']
|
|
58
|
+
REDIS_PORT = redis_config['REDIS_PORT']
|
|
59
|
+
REDIS_PASSWORD = redis_config['REDIS_PASSWORD']
|
|
60
|
+
REDIS_DB = redis_config['REDIS_DB']
|
|
61
|
+
|
|
131
62
|
# 🔧 根据是否有密码生成不同的 URL 格式
|
|
132
63
|
if REDIS_PASSWORD:
|
|
133
64
|
REDIS_URL = f'redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'
|
|
134
65
|
else:
|
|
135
66
|
REDIS_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'
|
|
136
|
-
|
|
67
|
+
|
|
68
|
+
# 统一的Redis key命名规范配置
|
|
69
|
+
# REDIS_KEY_PREFIX 已移至各组件中,使用统一的命名规范
|
|
70
|
+
# crawlo:{PROJECT_NAME}:filter:fingerprint (请求去重)
|
|
71
|
+
# crawlo:{PROJECT_NAME}:item:fingerprint (数据项去重)
|
|
72
|
+
# crawlo:{PROJECT_NAME}:queue:requests (请求队列)
|
|
73
|
+
# crawlo:{PROJECT_NAME}:queue:processing (处理中队列)
|
|
74
|
+
# crawlo:{PROJECT_NAME}:queue:failed (失败队列)
|
|
75
|
+
|
|
137
76
|
REDIS_TTL = 0 # 指纹过期时间(0 表示永不过期)
|
|
138
77
|
CLEANUP_FP = 0 # 程序结束时是否清理指纹(0=不清理)
|
|
139
78
|
FILTER_DEBUG = True # 是否开启去重调试日志
|
|
@@ -175,6 +114,10 @@ EXTENSIONS = [
|
|
|
175
114
|
'crawlo.extension.log_interval.LogIntervalExtension', # 定时日志
|
|
176
115
|
'crawlo.extension.log_stats.LogStats', # 统计信息
|
|
177
116
|
'crawlo.extension.logging_extension.CustomLoggerExtension', # 自定义日志
|
|
117
|
+
# 'crawlo.extension.memory_monitor.MemoryMonitorExtension', # 内存监控
|
|
118
|
+
# 'crawlo.extension.request_recorder.RequestRecorderExtension', # 请求记录
|
|
119
|
+
# 'crawlo.extension.performance_profiler.PerformanceProfilerExtension', # 性能分析
|
|
120
|
+
# 'crawlo.extension.health_check.HealthCheckExtension', # 健康检查
|
|
178
121
|
]
|
|
179
122
|
|
|
180
123
|
# ============================== 日志与监控 ==============================
|
|
@@ -240,6 +183,35 @@ HTTPX_FOLLOW_REDIRECTS = True # 是否自动跟随重定向
|
|
|
240
183
|
AIOHTTP_AUTO_DECOMPRESS = True # 是否自动解压响应
|
|
241
184
|
AIOHTTP_FORCE_CLOSE = False # 是否强制关闭连接
|
|
242
185
|
|
|
186
|
+
# ============================== Selenium 下载器配置 ==============================
|
|
187
|
+
|
|
188
|
+
# Selenium 基础配置
|
|
189
|
+
SELENIUM_BROWSER_TYPE = "chrome" # 浏览器类型: chrome, firefox, edge
|
|
190
|
+
SELENIUM_HEADLESS = True # 是否无头模式
|
|
191
|
+
SELENIUM_TIMEOUT = 30 # 超时时间(秒)
|
|
192
|
+
SELENIUM_LOAD_TIMEOUT = 10 # 页面加载超时时间(秒)
|
|
193
|
+
SELENIUM_WINDOW_WIDTH = 1920 # 窗口宽度
|
|
194
|
+
SELENIUM_WINDOW_HEIGHT = 1080 # 窗口高度
|
|
195
|
+
SELENIUM_WAIT_FOR_ELEMENT = None # 等待特定元素选择器
|
|
196
|
+
SELENIUM_ENABLE_JS = True # 是否启用JavaScript
|
|
197
|
+
SELENIUM_PROXY = None # 代理设置
|
|
198
|
+
SELENIUM_SINGLE_BROWSER_MODE = True # 单浏览器多标签页模式
|
|
199
|
+
SELENIUM_MAX_TABS_PER_BROWSER = 10 # 单浏览器最大标签页数量
|
|
200
|
+
|
|
201
|
+
# ============================== Playwright 下载器配置 ==============================
|
|
202
|
+
|
|
203
|
+
# Playwright 基础配置
|
|
204
|
+
PLAYWRIGHT_BROWSER_TYPE = "chromium" # 浏览器类型: chromium, firefox, webkit
|
|
205
|
+
PLAYWRIGHT_HEADLESS = True # 是否无头模式
|
|
206
|
+
PLAYWRIGHT_TIMEOUT = 30000 # 超时时间(毫秒)
|
|
207
|
+
PLAYWRIGHT_LOAD_TIMEOUT = 10000 # 页面加载超时时间(毫秒)
|
|
208
|
+
PLAYWRIGHT_VIEWPORT_WIDTH = 1920 # 视口宽度
|
|
209
|
+
PLAYWRIGHT_VIEWPORT_HEIGHT = 1080 # 视口高度
|
|
210
|
+
PLAYWRIGHT_WAIT_FOR_ELEMENT = None # 等待特定元素选择器
|
|
211
|
+
PLAYWRIGHT_PROXY = None # 代理设置
|
|
212
|
+
PLAYWRIGHT_SINGLE_BROWSER_MODE = True # 单浏览器多标签页模式
|
|
213
|
+
PLAYWRIGHT_MAX_PAGES_PER_BROWSER = 10 # 单浏览器最大页面数量
|
|
214
|
+
|
|
243
215
|
# 通用优化配置
|
|
244
216
|
CONNECTION_TTL_DNS_CACHE = 300 # DNS缓存TTL(秒)
|
|
245
217
|
CONNECTION_KEEPALIVE_TIMEOUT = 15 # Keep-Alive超时(秒)
|
crawlo/subscriber.py
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/python
|
|
2
2
|
# -*- coding:UTF-8 -*-
|
|
3
3
|
import asyncio
|
|
4
|
+
import weakref
|
|
4
5
|
from collections import defaultdict
|
|
5
6
|
from inspect import iscoroutinefunction
|
|
6
|
-
from typing import Dict, Set, Callable, Coroutine, Any, TypeAlias, List
|
|
7
|
+
from typing import Dict, Set, Callable, Coroutine, Any, TypeAlias, List, Tuple
|
|
7
8
|
|
|
8
9
|
|
|
9
10
|
class ReceiverTypeError(TypeError):
|
|
@@ -24,22 +25,30 @@ class Subscriber:
|
|
|
24
25
|
|
|
25
26
|
def __init__(self):
|
|
26
27
|
"""初始化一个空的订阅者字典。"""
|
|
27
|
-
|
|
28
|
+
# 使用弱引用字典避免内存泄漏
|
|
29
|
+
self._subscribers: Dict[str, Dict[ReceiverCoroutine, int]] = defaultdict(dict)
|
|
30
|
+
# 用于缓存排序后的订阅者列表,提高频繁事件的处理性能
|
|
31
|
+
self._sorted_subscribers_cache: Dict[str, List[Tuple[ReceiverCoroutine, int]]] = {}
|
|
28
32
|
|
|
29
|
-
def subscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
33
|
+
def subscribe(self, receiver: ReceiverCoroutine, *, event: str, priority: int = 0) -> None:
|
|
30
34
|
"""
|
|
31
35
|
订阅一个事件。
|
|
32
36
|
|
|
33
37
|
Args:
|
|
34
38
|
receiver: 一个协程函数 (例如 async def my_func(...))。
|
|
35
39
|
event: 要订阅的事件名称。
|
|
40
|
+
priority: 订阅者优先级,数值越小优先级越高,默认为0。
|
|
36
41
|
|
|
37
42
|
Raises:
|
|
38
43
|
ReceiverTypeError: 如果提供的 `receiver` 不是一个协程函数。
|
|
39
44
|
"""
|
|
40
45
|
if not iscoroutinefunction(receiver):
|
|
41
46
|
raise ReceiverTypeError(f"接收者 '{receiver.__qualname__}' 必须是一个协程函数。")
|
|
42
|
-
|
|
47
|
+
|
|
48
|
+
# 使用弱引用避免内存泄漏
|
|
49
|
+
self._subscribers[event][receiver] = priority
|
|
50
|
+
# 清除缓存
|
|
51
|
+
self._sorted_subscribers_cache.pop(event, None)
|
|
43
52
|
|
|
44
53
|
def unsubscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
45
54
|
"""
|
|
@@ -52,13 +61,47 @@ class Subscriber:
|
|
|
52
61
|
event: 事件名称。
|
|
53
62
|
"""
|
|
54
63
|
if event in self._subscribers:
|
|
55
|
-
self._subscribers[event].
|
|
64
|
+
self._subscribers[event].pop(receiver, None)
|
|
65
|
+
# 清除缓存
|
|
66
|
+
self._sorted_subscribers_cache.pop(event, None)
|
|
67
|
+
|
|
68
|
+
def _get_sorted_subscribers(self, event: str) -> List[Tuple[ReceiverCoroutine, int]]:
|
|
69
|
+
"""
|
|
70
|
+
获取按优先级排序的订阅者列表。
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
event: 事件名称。
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
按优先级排序的订阅者列表。
|
|
77
|
+
"""
|
|
78
|
+
# 检查缓存
|
|
79
|
+
if event in self._sorted_subscribers_cache:
|
|
80
|
+
return self._sorted_subscribers_cache[event]
|
|
81
|
+
|
|
82
|
+
# 获取有效的订阅者(使用弱引用检查)
|
|
83
|
+
valid_subscribers = {}
|
|
84
|
+
for receiver, priority in list(self._subscribers[event].items()):
|
|
85
|
+
# 检查弱引用是否仍然有效
|
|
86
|
+
if isinstance(receiver, Callable):
|
|
87
|
+
valid_subscribers[receiver] = priority
|
|
88
|
+
|
|
89
|
+
# 更新订阅者字典
|
|
90
|
+
self._subscribers[event] = valid_subscribers
|
|
91
|
+
|
|
92
|
+
# 按优先级排序(数值小的优先级高)
|
|
93
|
+
sorted_subscribers = sorted(valid_subscribers.items(), key=lambda x: x[1])
|
|
94
|
+
# 缓存结果
|
|
95
|
+
self._sorted_subscribers_cache[event] = sorted_subscribers
|
|
96
|
+
|
|
97
|
+
return sorted_subscribers
|
|
56
98
|
|
|
57
99
|
async def notify(self, event: str, *args, **kwargs) -> List[Any]:
|
|
58
100
|
"""
|
|
59
101
|
异步地、并发地通知所有订阅了该事件的接收者。
|
|
60
102
|
|
|
61
103
|
此方法会等待所有订阅者任务完成后再返回,并收集所有结果或异常。
|
|
104
|
+
订阅者按优先级顺序执行,优先级高的先执行。
|
|
62
105
|
|
|
63
106
|
Args:
|
|
64
107
|
event: 要触发的事件名称。
|
|
@@ -68,39 +111,21 @@ class Subscriber:
|
|
|
68
111
|
Returns:
|
|
69
112
|
一个列表,包含每个订阅者任务的返回结果或在执行期间捕获的异常。
|
|
70
113
|
"""
|
|
71
|
-
|
|
72
|
-
if not
|
|
114
|
+
sorted_subscribers = self._get_sorted_subscribers(event)
|
|
115
|
+
if not sorted_subscribers:
|
|
73
116
|
return []
|
|
74
117
|
|
|
75
|
-
|
|
118
|
+
# 为频繁触发的事件重用任务对象以提高性能
|
|
119
|
+
tasks = []
|
|
120
|
+
for receiver, _ in sorted_subscribers:
|
|
121
|
+
try:
|
|
122
|
+
# 创建任务并添加到列表
|
|
123
|
+
task = asyncio.create_task(receiver(*args, **kwargs))
|
|
124
|
+
tasks.append(task)
|
|
125
|
+
except Exception as e:
|
|
126
|
+
# 如果创建任务失败,记录异常并继续处理其他订阅者
|
|
127
|
+
tasks.append(asyncio.Future()) # 添加一个已完成的Future表示错误
|
|
128
|
+
tasks[-1].set_exception(e)
|
|
76
129
|
|
|
77
130
|
# 并发执行所有任务并返回结果列表(包括异常)
|
|
78
|
-
return await asyncio.gather(*tasks, return_exceptions=True)
|
|
79
|
-
|
|
80
|
-
# #!/usr/bin/python
|
|
81
|
-
# # -*- coding:UTF-8 -*-
|
|
82
|
-
# import asyncio
|
|
83
|
-
# from collections import defaultdict
|
|
84
|
-
# from inspect import iscoroutinefunction
|
|
85
|
-
# from typing import Dict, Set, Callable, Coroutine
|
|
86
|
-
#
|
|
87
|
-
# from crawlo.exceptions import ReceiverTypeError
|
|
88
|
-
#
|
|
89
|
-
#
|
|
90
|
-
# class Subscriber:
|
|
91
|
-
#
|
|
92
|
-
# def __init__(self):
|
|
93
|
-
# self._subscribers: Dict[str, Set[Callable[..., Coroutine]]] = defaultdict(set)
|
|
94
|
-
#
|
|
95
|
-
# def subscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
96
|
-
# if not iscoroutinefunction(receiver):
|
|
97
|
-
# raise ReceiverTypeError(f"{receiver.__qualname__} must be a coroutine function")
|
|
98
|
-
# self._subscribers[event].add(receiver)
|
|
99
|
-
#
|
|
100
|
-
# def unsubscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
101
|
-
# self._subscribers[event].discard(receiver)
|
|
102
|
-
#
|
|
103
|
-
# async def notify(self, event: str, *args, **kwargs) -> None:
|
|
104
|
-
# for receiver in self._subscribers[event]:
|
|
105
|
-
# # 不能 await
|
|
106
|
-
# asyncio.create_task(receiver(*args, **kwargs))
|
|
131
|
+
return await asyncio.gather(*tasks, return_exceptions=True)
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
{{project_name}}.middlewares
|
|
4
4
|
============================
|
|
5
5
|
自定义中间件,用于在请求/响应/异常处理过程中插入自定义逻辑。
|
|
6
|
+
|
|
7
|
+
这是一个简单的示例中间件,您可以根据需要添加更多中间件。
|
|
6
8
|
"""
|
|
7
9
|
|
|
8
10
|
import random
|
|
@@ -11,8 +13,15 @@ from crawlo.utils.log import get_logger
|
|
|
11
13
|
from crawlo.exceptions import IgnoreRequest
|
|
12
14
|
|
|
13
15
|
|
|
14
|
-
class
|
|
15
|
-
"""
|
|
16
|
+
class ExampleMiddleware:
|
|
17
|
+
"""
|
|
18
|
+
示例中间件,演示如何处理请求、响应和异常。
|
|
19
|
+
|
|
20
|
+
此中间件会:
|
|
21
|
+
1. 为请求添加随机 User-Agent
|
|
22
|
+
2. 记录请求和响应信息
|
|
23
|
+
3. 处理异常情况
|
|
24
|
+
"""
|
|
16
25
|
|
|
17
26
|
def __init__(self):
|
|
18
27
|
self.logger = get_logger(self.__class__.__name__)
|
|
@@ -22,66 +31,81 @@ class RandomUserAgentMiddleware:
|
|
|
22
31
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
23
32
|
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
24
33
|
]
|
|
25
|
-
|
|
34
|
+
|
|
26
35
|
def process_request(self, request, spider):
|
|
36
|
+
"""
|
|
37
|
+
在请求被下载器执行前调用。
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
request: 请求对象
|
|
41
|
+
spider: 爬虫实例
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
None: 继续处理请求
|
|
45
|
+
Response: 返回响应对象(短路处理)
|
|
46
|
+
Request: 返回新请求对象(替换原请求)
|
|
47
|
+
"""
|
|
48
|
+
# 为请求添加随机 User-Agent
|
|
27
49
|
if 'User-Agent' not in request.headers:
|
|
28
50
|
ua = random.choice(self.user_agents)
|
|
29
51
|
request.headers['User-Agent'] = ua
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
class CustomDownloaderMiddleware:
|
|
34
|
-
"""自定义下载器中间件示例。"""
|
|
35
|
-
|
|
36
|
-
def __init__(self):
|
|
37
|
-
self.logger = get_logger(self.__class__.__name__)
|
|
38
|
-
|
|
39
|
-
def process_request(self, request, spider):
|
|
40
|
-
"""在请求被下载器执行前调用。"""
|
|
41
|
-
# 示例:添加自定义请求头
|
|
42
|
-
# request.headers['Custom-Header'] = 'Custom-Value'
|
|
43
|
-
# 示例:设置代理
|
|
44
|
-
# request.meta['proxy'] = 'http://proxy.example.com:8080'
|
|
52
|
+
self.logger.debug(f"为请求 {request.url} 设置 User-Agent: {ua[:50]}...")
|
|
53
|
+
|
|
45
54
|
return None
|
|
46
55
|
|
|
47
56
|
def process_response(self, request, response, spider):
|
|
48
|
-
"""
|
|
49
|
-
|
|
57
|
+
"""
|
|
58
|
+
在响应被 Spider 处理前调用。
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
request: 原始请求对象
|
|
62
|
+
response: 响应对象
|
|
63
|
+
spider: 爬虫实例
|
|
64
|
+
|
|
65
|
+
Returns:
|
|
66
|
+
Response: 处理后的响应对象
|
|
67
|
+
"""
|
|
68
|
+
# 记录响应信息
|
|
69
|
+
self.logger.info(f"收到响应: {request.url} - 状态码: {response.status_code}")
|
|
70
|
+
|
|
71
|
+
# 可以在这里处理特殊状态码
|
|
50
72
|
if response.status_code == 403:
|
|
51
73
|
self.logger.warning(f"访问被拒绝: {request.url}")
|
|
74
|
+
|
|
52
75
|
return response
|
|
53
76
|
|
|
54
77
|
def process_exception(self, request, exception, spider):
|
|
55
|
-
"""
|
|
78
|
+
"""
|
|
79
|
+
在下载或处理过程中发生异常时调用。
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
request: 请求对象
|
|
83
|
+
exception: 异常对象
|
|
84
|
+
spider: 爬虫实例
|
|
85
|
+
|
|
86
|
+
Returns:
|
|
87
|
+
None: 异常将继续传播
|
|
88
|
+
Response: 返回响应对象(处理异常)
|
|
89
|
+
Request: 返回新请求对象(重试请求)
|
|
90
|
+
"""
|
|
56
91
|
self.logger.error(f"请求异常: {request.url} - {exception}")
|
|
57
92
|
return None
|
|
58
93
|
|
|
59
94
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
yield item
|
|
78
|
-
|
|
79
|
-
def process_spider_exception(self, response, exception, spider):
|
|
80
|
-
"""在 Spider 的 parse 方法抛出异常时调用。"""
|
|
81
|
-
self.logger.error(f"Spider 异常: {response.url} - {exception}")
|
|
82
|
-
pass
|
|
83
|
-
|
|
84
|
-
def process_start_requests(self, start_requests, spider):
|
|
85
|
-
"""在 Spider 的 start_requests 生成器被消费时调用。"""
|
|
86
|
-
for request in start_requests:
|
|
87
|
-
yield request
|
|
95
|
+
# ======================== 使用说明 ========================
|
|
96
|
+
#
|
|
97
|
+
# 在 settings.py 中启用中间件:
|
|
98
|
+
# MIDDLEWARES = [
|
|
99
|
+
# '{{project_name}}.middlewares.ExampleMiddleware',
|
|
100
|
+
# ]
|
|
101
|
+
#
|
|
102
|
+
# 您可以根据需要添加更多中间件,例如:
|
|
103
|
+
# 1. 请求处理中间件(修改请求头、设置代理等)
|
|
104
|
+
# 2. 响应处理中间件(解析、过滤等)
|
|
105
|
+
# 3. 异常处理中间件(重试、记录等)
|
|
106
|
+
#
|
|
107
|
+
# 每个中间件可以实现以下方法:
|
|
108
|
+
# - process_request: 处理请求
|
|
109
|
+
# - process_response: 处理响应
|
|
110
|
+
# - process_exception: 处理异常
|
|
111
|
+
# ======================== 使用说明 ========================
|