crawlo 1.1.1__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.

Files changed (68) hide show
  1. crawlo/__init__.py +2 -1
  2. crawlo/__version__.py +1 -1
  3. crawlo/commands/genspider.py +68 -42
  4. crawlo/commands/list.py +102 -93
  5. crawlo/commands/startproject.py +89 -4
  6. crawlo/commands/utils.py +187 -0
  7. crawlo/config.py +280 -0
  8. crawlo/core/engine.py +16 -3
  9. crawlo/core/enhanced_engine.py +190 -0
  10. crawlo/core/scheduler.py +113 -8
  11. crawlo/crawler.py +840 -307
  12. crawlo/downloader/__init__.py +181 -17
  13. crawlo/downloader/aiohttp_downloader.py +15 -2
  14. crawlo/downloader/cffi_downloader.py +11 -1
  15. crawlo/downloader/httpx_downloader.py +14 -3
  16. crawlo/filters/__init__.py +122 -5
  17. crawlo/filters/aioredis_filter.py +128 -36
  18. crawlo/filters/memory_filter.py +99 -32
  19. crawlo/middleware/proxy.py +11 -8
  20. crawlo/middleware/retry.py +40 -5
  21. crawlo/mode_manager.py +201 -0
  22. crawlo/network/__init__.py +17 -3
  23. crawlo/network/request.py +118 -10
  24. crawlo/network/response.py +131 -28
  25. crawlo/pipelines/__init__.py +1 -1
  26. crawlo/pipelines/csv_pipeline.py +317 -0
  27. crawlo/pipelines/json_pipeline.py +219 -0
  28. crawlo/queue/__init__.py +0 -0
  29. crawlo/queue/pqueue.py +37 -0
  30. crawlo/queue/queue_manager.py +304 -0
  31. crawlo/queue/redis_priority_queue.py +192 -0
  32. crawlo/settings/default_settings.py +68 -9
  33. crawlo/spider/__init__.py +576 -66
  34. crawlo/task_manager.py +4 -1
  35. crawlo/templates/project/middlewares.py.tmpl +56 -45
  36. crawlo/templates/project/pipelines.py.tmpl +308 -36
  37. crawlo/templates/project/run.py.tmpl +239 -0
  38. crawlo/templates/project/settings.py.tmpl +211 -17
  39. crawlo/templates/spider/spider.py.tmpl +153 -7
  40. crawlo/utils/controlled_spider_mixin.py +336 -0
  41. crawlo/utils/large_scale_config.py +287 -0
  42. crawlo/utils/large_scale_helper.py +344 -0
  43. crawlo/utils/queue_helper.py +176 -0
  44. crawlo/utils/request_serializer.py +220 -0
  45. crawlo-1.1.2.dist-info/METADATA +567 -0
  46. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
  47. tests/test_final_validation.py +154 -0
  48. tests/test_redis_config.py +29 -0
  49. tests/test_redis_queue.py +225 -0
  50. tests/test_request_serialization.py +71 -0
  51. tests/test_scheduler.py +242 -0
  52. crawlo/pipelines/mysql_batch_pipline.py +0 -273
  53. crawlo/utils/pqueue.py +0 -174
  54. crawlo-1.1.1.dist-info/METADATA +0 -220
  55. examples/baidu_spider/__init__.py +0 -7
  56. examples/baidu_spider/demo.py +0 -94
  57. examples/baidu_spider/items.py +0 -46
  58. examples/baidu_spider/middleware.py +0 -49
  59. examples/baidu_spider/pipeline.py +0 -55
  60. examples/baidu_spider/run.py +0 -27
  61. examples/baidu_spider/settings.py +0 -121
  62. examples/baidu_spider/spiders/__init__.py +0 -7
  63. examples/baidu_spider/spiders/bai_du.py +0 -61
  64. examples/baidu_spider/spiders/miit.py +0 -159
  65. examples/baidu_spider/spiders/sina.py +0 -79
  66. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
  67. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
  68. {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,187 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ 命令行工具公共模块
5
+ 提供命令行工具的公共函数和工具
6
+ """
7
+ import sys
8
+ import configparser
9
+ from pathlib import Path
10
+ from importlib import import_module
11
+ from typing import Optional, Tuple
12
+
13
+ from rich.console import Console
14
+ from rich.panel import Panel
15
+ from rich.text import Text
16
+
17
+ console = Console()
18
+
19
+
20
+ def get_project_root() -> Optional[Path]:
21
+ """
22
+ 自动检测项目根目录:从当前目录向上查找 crawlo.cfg
23
+
24
+ Returns:
25
+ Path: 项目根目录路径,如果未找到返回 None
26
+ """
27
+ current = Path.cwd()
28
+ for _ in range(10): # 最多向上查找10层
29
+ cfg_file = current / "crawlo.cfg"
30
+ if cfg_file.exists():
31
+ return current
32
+ if current == current.parent:
33
+ break
34
+ current = current.parent
35
+ return None
36
+
37
+
38
+ def validate_project_environment() -> Tuple[bool, Optional[str], Optional[str]]:
39
+ """
40
+ 验证项目环境,确保在正确的 Crawlo 项目中
41
+
42
+ Returns:
43
+ Tuple[bool, Optional[str], Optional[str]]:
44
+ (是否有效, 项目包名, 错误信息)
45
+ """
46
+ # 1. 查找项目根目录
47
+ project_root = get_project_root()
48
+ if not project_root:
49
+ return False, None, "Cannot find 'crawlo.cfg'. Run this command inside your project directory."
50
+
51
+ # 2. 将项目根加入 Python 路径
52
+ project_root_str = str(project_root)
53
+ if project_root_str not in sys.path:
54
+ sys.path.insert(0, project_root_str)
55
+
56
+ # 3. 读取配置文件
57
+ cfg_file = project_root / "crawlo.cfg"
58
+ config = configparser.ConfigParser()
59
+
60
+ try:
61
+ config.read(cfg_file, encoding="utf-8")
62
+ except Exception as e:
63
+ return False, None, f"Failed to read crawlo.cfg: {e}"
64
+
65
+ if not config.has_section("settings") or not config.has_option("settings", "default"):
66
+ return False, None, "Invalid crawlo.cfg: missing [settings] section or 'default' option"
67
+
68
+ # 4. 获取项目包名
69
+ settings_module = config.get("settings", "default")
70
+ project_package = settings_module.split(".")[0]
71
+
72
+ # 5. 验证项目包是否可导入
73
+ try:
74
+ import_module(project_package)
75
+ except ImportError as e:
76
+ return False, None, f"Failed to import project package '{project_package}': {e}"
77
+
78
+ return True, project_package, None
79
+
80
+
81
+ def show_error_panel(title: str, message: str, show_json: bool = False) -> None:
82
+ """
83
+ 显示错误面板或JSON格式错误
84
+
85
+ Args:
86
+ title: 错误标题
87
+ message: 错误消息
88
+ show_json: 是否以JSON格式输出
89
+ """
90
+ if show_json:
91
+ console.print_json(data={"success": False, "error": message})
92
+ else:
93
+ console.print(Panel(
94
+ Text.from_markup(f":cross_mark: [bold red]{message}[/bold red]"),
95
+ title=f"❌ {title}",
96
+ border_style="red",
97
+ padding=(1, 2)
98
+ ))
99
+
100
+
101
+ def show_success_panel(title: str, message: str, show_json: bool = False, data: dict = None) -> None:
102
+ """
103
+ 显示成功面板或JSON格式结果
104
+
105
+ Args:
106
+ title: 成功标题
107
+ message: 成功消息
108
+ show_json: 是否以JSON格式输出
109
+ data: JSON数据(当show_json=True时)
110
+ """
111
+ if show_json:
112
+ result = {"success": True, "message": message}
113
+ if data:
114
+ result.update(data)
115
+ console.print_json(data=result)
116
+ else:
117
+ console.print(Panel(
118
+ Text.from_markup(f":white_check_mark: [bold green]{message}[/bold green]"),
119
+ title=f"✅ {title}",
120
+ border_style="green",
121
+ padding=(1, 2)
122
+ ))
123
+
124
+
125
+ def validate_spider_name(spider_name: str) -> bool:
126
+ """
127
+ 验证爬虫名称是否符合规范
128
+
129
+ Args:
130
+ spider_name: 爬虫名称
131
+
132
+ Returns:
133
+ bool: 是否有效
134
+ """
135
+ import re
136
+ # 爬虫名称应该是有效的Python标识符
137
+ return spider_name.isidentifier() and re.match(r'^[a-z][a-z0-9_]*$', spider_name)
138
+
139
+
140
+ def format_file_size(size_bytes: int) -> str:
141
+ """
142
+ 格式化文件大小
143
+
144
+ Args:
145
+ size_bytes: 字节数
146
+
147
+ Returns:
148
+ str: 格式化后的大小字符串
149
+ """
150
+ for unit in ['B', 'KB', 'MB', 'GB']:
151
+ if size_bytes < 1024.0:
152
+ return f"{size_bytes:.1f} {unit}"
153
+ size_bytes /= 1024.0
154
+ return f"{size_bytes:.1f} TB"
155
+
156
+
157
+ def truncate_text(text: str, max_length: int = 80) -> str:
158
+ """
159
+ 截断过长的文本
160
+
161
+ Args:
162
+ text: 原始文本
163
+ max_length: 最大长度
164
+
165
+ Returns:
166
+ str: 截断后的文本
167
+ """
168
+ if len(text) <= max_length:
169
+ return text
170
+ return text[:max_length-3] + "..."
171
+
172
+
173
+ def is_valid_domain(domain: str) -> bool:
174
+ """
175
+ 验证域名格式是否正确
176
+
177
+ Args:
178
+ domain: 域名
179
+
180
+ Returns:
181
+ bool: 是否有效
182
+ """
183
+ import re
184
+ pattern = re.compile(
185
+ r'^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$'
186
+ )
187
+ return bool(pattern.match(domain))
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/engine.py CHANGED
@@ -34,6 +34,19 @@ class Engine(object):
34
34
  self.logger = get_logger(name=self.__class__.__name__)
35
35
 
36
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 完整类路径(兼容旧版本)
37
50
  downloader_cls = load_class(self.settings.get('DOWNLOADER'))
38
51
  if not issubclass(downloader_cls, DownloaderBase):
39
52
  raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
@@ -51,7 +64,7 @@ class Engine(object):
51
64
 
52
65
  self.scheduler = Scheduler.create_instance(self.crawler)
53
66
  if hasattr(self.scheduler, 'open'):
54
- self.scheduler.open()
67
+ await self.scheduler.open()
55
68
 
56
69
  downloader_cls = self._get_downloader_cls()
57
70
  self.downloader = downloader_cls(self.crawler)
@@ -105,8 +118,8 @@ class Engine(object):
105
118
  if outputs:
106
119
  await self._handle_spider_output(outputs)
107
120
 
108
- # asyncio.create_task(crawl_task())
109
- self.task_manager.create_task(crawl_task())
121
+ # 使用异步任务创建,遵守并发限制
122
+ await self.task_manager.create_task(crawl_task())
110
123
 
111
124
  async def _fetch(self, request):
112
125
  async def _successful(_response):
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ 增强的引擎实现
5
+ 解决大规模请求生成时的并发控制和背压问题
6
+ """
7
+ import asyncio
8
+
9
+ from crawlo.core.engine import Engine as BaseEngine
10
+ from crawlo.utils.log import get_logger
11
+
12
+
13
+ class EnhancedEngine(BaseEngine):
14
+ """
15
+ 增强的引擎实现
16
+
17
+ 主要改进:
18
+ 1. 智能的请求生成控制
19
+ 2. 背压感知的调度
20
+ 3. 动态并发调整
21
+ """
22
+
23
+ def __init__(self, crawler):
24
+ super().__init__(crawler)
25
+
26
+ # 增强控制参数
27
+ self.max_queue_size = self.settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 200)
28
+ self.generation_batch_size = 10
29
+ self.generation_interval = 0.05
30
+ self.backpressure_ratio = 0.8 # 队列达到80%时启动背压
31
+
32
+ # 状态跟踪
33
+ self._generation_paused = False
34
+ self._last_generation_time = 0
35
+ self._generation_stats = {
36
+ 'total_generated': 0,
37
+ 'backpressure_events': 0
38
+ }
39
+
40
+ self.logger = get_logger(self.__class__.__name__)
41
+
42
+ async def crawl(self):
43
+ """
44
+ 增强的爬取循环
45
+ 支持智能请求生成和背压控制
46
+ """
47
+ generation_task = None
48
+
49
+ try:
50
+ # 启动请求生成任务
51
+ if self.start_requests:
52
+ generation_task = asyncio.create_task(
53
+ self._controlled_request_generation()
54
+ )
55
+
56
+ # 主爬取循环
57
+ while self.running:
58
+ # 获取并处理请求
59
+ if request := await self._get_next_request():
60
+ await self._crawl(request)
61
+
62
+ # 检查退出条件
63
+ if await self._should_exit():
64
+ break
65
+
66
+ # 短暂休息避免忙等
67
+ await asyncio.sleep(0.001)
68
+
69
+ finally:
70
+ # 清理生成任务
71
+ if generation_task and not generation_task.done():
72
+ generation_task.cancel()
73
+ try:
74
+ await generation_task
75
+ except asyncio.CancelledError:
76
+ pass
77
+
78
+ await self.close_spider()
79
+
80
+ async def _controlled_request_generation(self):
81
+ """受控的请求生成"""
82
+ self.logger.info("🎛️ 启动受控请求生成")
83
+
84
+ batch = []
85
+ total_generated = 0
86
+
87
+ try:
88
+ for request in self.start_requests:
89
+ batch.append(request)
90
+
91
+ # 批量处理
92
+ if len(batch) >= self.generation_batch_size:
93
+ generated = await self._process_generation_batch(batch)
94
+ total_generated += generated
95
+ batch = []
96
+
97
+ # 背压检查
98
+ if await self._should_pause_generation():
99
+ await self._wait_for_capacity()
100
+
101
+ # 处理剩余请求
102
+ if batch:
103
+ generated = await self._process_generation_batch(batch)
104
+ total_generated += generated
105
+
106
+ except Exception as e:
107
+ self.logger.error(f"❌ 请求生成失败: {e}")
108
+
109
+ finally:
110
+ self.start_requests = None
111
+ self.logger.info(f"🎉 请求生成完成,总计: {total_generated}")
112
+
113
+ async def _process_generation_batch(self, batch) -> int:
114
+ """处理一批请求"""
115
+ generated = 0
116
+
117
+ for request in batch:
118
+ if not self.running:
119
+ break
120
+
121
+ # 等待队列有空间
122
+ while await self._is_queue_full() and self.running:
123
+ await asyncio.sleep(0.1)
124
+
125
+ if self.running:
126
+ await self.enqueue_request(request)
127
+ generated += 1
128
+ self._generation_stats['total_generated'] += 1
129
+
130
+ # 控制生成速度
131
+ if self.generation_interval > 0:
132
+ await asyncio.sleep(self.generation_interval)
133
+
134
+ return generated
135
+
136
+ async def _should_pause_generation(self) -> bool:
137
+ """判断是否应该暂停生成"""
138
+ # 检查队列大小
139
+ if await self._is_queue_full():
140
+ return True
141
+
142
+ # 检查任务管理器负载
143
+ if self.task_manager:
144
+ current_tasks = len(self.task_manager.current_task)
145
+ if hasattr(self.task_manager, 'semaphore'):
146
+ max_concurrency = getattr(self.task_manager.semaphore, '_initial_value', 8)
147
+ if current_tasks >= max_concurrency * self.backpressure_ratio:
148
+ return True
149
+
150
+ return False
151
+
152
+ async def _is_queue_full(self) -> bool:
153
+ """检查队列是否已满"""
154
+ if not self.scheduler:
155
+ return False
156
+
157
+ queue_size = len(self.scheduler)
158
+ return queue_size >= self.max_queue_size * self.backpressure_ratio
159
+
160
+ async def _wait_for_capacity(self):
161
+ """等待系统有足够容量"""
162
+ self._generation_stats['backpressure_events'] += 1
163
+ self.logger.debug("⏸️ 触发背压,暂停请求生成")
164
+
165
+ wait_time = 0.1
166
+ max_wait = 2.0
167
+
168
+ while await self._should_pause_generation() and self.running:
169
+ await asyncio.sleep(wait_time)
170
+ wait_time = min(wait_time * 1.1, max_wait)
171
+
172
+ async def _should_exit(self) -> bool:
173
+ """检查是否应该退出"""
174
+ # 没有启动请求,且所有队列都空闲
175
+ if (self.start_requests is None and
176
+ self.scheduler.idle() and
177
+ self.downloader.idle() and
178
+ self.task_manager.all_done() and
179
+ self.processor.idle()):
180
+ return True
181
+
182
+ return False
183
+
184
+ def get_generation_stats(self) -> dict:
185
+ """获取生成统计"""
186
+ return {
187
+ **self._generation_stats,
188
+ 'queue_size': len(self.scheduler) if self.scheduler else 0,
189
+ 'active_tasks': len(self.task_manager.current_task) if self.task_manager else 0
190
+ }