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.

Files changed (115) hide show
  1. crawlo/__init__.py +28 -1
  2. crawlo/__version__.py +1 -1
  3. crawlo/cleaners/__init__.py +61 -0
  4. crawlo/cleaners/data_formatter.py +226 -0
  5. crawlo/cleaners/encoding_converter.py +126 -0
  6. crawlo/cleaners/text_cleaner.py +233 -0
  7. crawlo/commands/startproject.py +117 -13
  8. crawlo/config.py +30 -0
  9. crawlo/config_validator.py +253 -0
  10. crawlo/core/engine.py +185 -11
  11. crawlo/core/scheduler.py +49 -78
  12. crawlo/crawler.py +6 -6
  13. crawlo/downloader/__init__.py +24 -0
  14. crawlo/downloader/aiohttp_downloader.py +8 -0
  15. crawlo/downloader/cffi_downloader.py +5 -0
  16. crawlo/downloader/hybrid_downloader.py +214 -0
  17. crawlo/downloader/playwright_downloader.py +403 -0
  18. crawlo/downloader/selenium_downloader.py +473 -0
  19. crawlo/extension/__init__.py +17 -10
  20. crawlo/extension/health_check.py +142 -0
  21. crawlo/extension/log_interval.py +27 -18
  22. crawlo/extension/log_stats.py +62 -24
  23. crawlo/extension/logging_extension.py +18 -9
  24. crawlo/extension/memory_monitor.py +105 -0
  25. crawlo/extension/performance_profiler.py +134 -0
  26. crawlo/extension/request_recorder.py +108 -0
  27. crawlo/filters/aioredis_filter.py +50 -12
  28. crawlo/middleware/proxy.py +26 -2
  29. crawlo/mode_manager.py +24 -19
  30. crawlo/network/request.py +30 -3
  31. crawlo/network/response.py +114 -25
  32. crawlo/pipelines/mongo_pipeline.py +81 -66
  33. crawlo/pipelines/mysql_pipeline.py +165 -43
  34. crawlo/pipelines/redis_dedup_pipeline.py +7 -3
  35. crawlo/queue/queue_manager.py +15 -2
  36. crawlo/queue/redis_priority_queue.py +144 -76
  37. crawlo/settings/default_settings.py +93 -121
  38. crawlo/subscriber.py +62 -37
  39. crawlo/templates/project/items.py.tmpl +1 -1
  40. crawlo/templates/project/middlewares.py.tmpl +73 -49
  41. crawlo/templates/project/pipelines.py.tmpl +51 -295
  42. crawlo/templates/project/settings.py.tmpl +93 -17
  43. crawlo/templates/project/settings_distributed.py.tmpl +120 -0
  44. crawlo/templates/project/settings_gentle.py.tmpl +95 -0
  45. crawlo/templates/project/settings_high_performance.py.tmpl +152 -0
  46. crawlo/templates/project/settings_simple.py.tmpl +69 -0
  47. crawlo/templates/spider/spider.py.tmpl +2 -38
  48. crawlo/tools/__init__.py +183 -0
  49. crawlo/tools/anti_crawler.py +269 -0
  50. crawlo/tools/authenticated_proxy.py +241 -0
  51. crawlo/tools/data_validator.py +181 -0
  52. crawlo/tools/date_tools.py +36 -0
  53. crawlo/tools/distributed_coordinator.py +387 -0
  54. crawlo/tools/retry_mechanism.py +221 -0
  55. crawlo/tools/scenario_adapter.py +263 -0
  56. crawlo/utils/__init__.py +29 -1
  57. crawlo/utils/batch_processor.py +261 -0
  58. crawlo/utils/date_tools.py +58 -1
  59. crawlo/utils/enhanced_error_handler.py +360 -0
  60. crawlo/utils/env_config.py +106 -0
  61. crawlo/utils/error_handler.py +126 -0
  62. crawlo/utils/performance_monitor.py +285 -0
  63. crawlo/utils/redis_connection_pool.py +335 -0
  64. crawlo/utils/redis_key_validator.py +200 -0
  65. crawlo-1.1.5.dist-info/METADATA +401 -0
  66. crawlo-1.1.5.dist-info/RECORD +185 -0
  67. tests/advanced_tools_example.py +276 -0
  68. tests/authenticated_proxy_example.py +237 -0
  69. tests/cleaners_example.py +161 -0
  70. tests/config_validation_demo.py +103 -0
  71. tests/date_tools_example.py +181 -0
  72. tests/dynamic_loading_example.py +524 -0
  73. tests/dynamic_loading_test.py +105 -0
  74. tests/env_config_example.py +134 -0
  75. tests/error_handling_example.py +172 -0
  76. tests/redis_key_validation_demo.py +131 -0
  77. tests/response_improvements_example.py +145 -0
  78. tests/test_advanced_tools.py +149 -0
  79. tests/test_all_redis_key_configs.py +146 -0
  80. tests/test_authenticated_proxy.py +142 -0
  81. tests/test_cleaners.py +55 -0
  82. tests/test_comprehensive.py +147 -0
  83. tests/test_config_validator.py +194 -0
  84. tests/test_date_tools.py +124 -0
  85. tests/test_dynamic_downloaders_proxy.py +125 -0
  86. tests/test_dynamic_proxy.py +93 -0
  87. tests/test_dynamic_proxy_config.py +147 -0
  88. tests/test_dynamic_proxy_real.py +110 -0
  89. tests/test_edge_cases.py +304 -0
  90. tests/test_enhanced_error_handler.py +271 -0
  91. tests/test_env_config.py +122 -0
  92. tests/test_error_handler_compatibility.py +113 -0
  93. tests/test_framework_env_usage.py +104 -0
  94. tests/test_integration.py +357 -0
  95. tests/test_item_dedup_redis_key.py +123 -0
  96. tests/test_parsel.py +30 -0
  97. tests/test_performance.py +328 -0
  98. tests/test_queue_manager_redis_key.py +177 -0
  99. tests/test_redis_connection_pool.py +295 -0
  100. tests/test_redis_key_naming.py +182 -0
  101. tests/test_redis_key_validator.py +124 -0
  102. tests/test_response_improvements.py +153 -0
  103. tests/test_simple_response.py +62 -0
  104. tests/test_telecom_spider_redis_key.py +206 -0
  105. tests/test_template_content.py +88 -0
  106. tests/test_template_redis_key.py +135 -0
  107. tests/test_tools.py +154 -0
  108. tests/tools_example.py +258 -0
  109. crawlo/core/enhanced_engine.py +0 -190
  110. crawlo-1.1.3.dist-info/METADATA +0 -635
  111. crawlo-1.1.3.dist-info/RECORD +0 -113
  112. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/WHEEL +0 -0
  113. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/entry_points.txt +0 -0
  114. {crawlo-1.1.3.dist-info → crawlo-1.1.5.dist-info}/top_level.txt +0 -0
  115. {examples → tests}/controlled_spider_example.py +0 -0
tests/test_tools.py ADDED
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ 工具包测试
5
+ """
6
+ import unittest
7
+ from crawlo.tools import (
8
+ # 日期工具
9
+ parse_time,
10
+ format_time,
11
+ time_diff,
12
+
13
+ # 数据清洗工具
14
+ clean_text,
15
+ format_currency,
16
+ extract_emails,
17
+
18
+ # 数据验证工具
19
+ validate_email,
20
+ validate_url,
21
+ validate_phone,
22
+ validate_chinese_id_card,
23
+ validate_date,
24
+ validate_number_range,
25
+
26
+ # 请求处理工具
27
+ build_url,
28
+ add_query_params,
29
+ merge_headers,
30
+
31
+ # 反爬虫应对工具
32
+ get_random_user_agent,
33
+ rotate_proxy,
34
+
35
+ # 分布式协调工具
36
+ generate_task_id,
37
+ get_cluster_info
38
+ )
39
+
40
+
41
+ class TestTools(unittest.TestCase):
42
+ """工具包测试类"""
43
+
44
+ def test_date_tools(self):
45
+ """测试日期工具"""
46
+ # 测试时间解析
47
+ time_str = "2025-09-10 14:30:00"
48
+ parsed_time = parse_time(time_str)
49
+ self.assertIsNotNone(parsed_time)
50
+
51
+ # 测试时间格式化
52
+ formatted_time = format_time(parsed_time, "%Y-%m-%d")
53
+ self.assertEqual(formatted_time, "2025-09-10")
54
+
55
+ # 测试时间差计算
56
+ time_str2 = "2025-09-11 14:30:00"
57
+ parsed_time2 = parse_time(time_str2)
58
+ diff = time_diff(parsed_time2, parsed_time)
59
+ self.assertEqual(diff, 86400) # 24小时 = 86400秒
60
+
61
+ def test_data_cleaning_tools(self):
62
+ """测试数据清洗工具"""
63
+ # 测试文本清洗
64
+ dirty_text = "<p>这是一个&nbsp;<b>测试</b>&amp;文本</p>"
65
+ clean_result = clean_text(dirty_text)
66
+ self.assertEqual(clean_result, "这是一个 测试&文本")
67
+
68
+ # 测试货币格式化
69
+ price = 1234.567
70
+ formatted_price = format_currency(price, "¥", 2)
71
+ self.assertEqual(formatted_price, "¥1,234.57")
72
+
73
+ # 测试邮箱提取
74
+ text_with_email = "联系邮箱: test@example.com, support@crawler.com"
75
+ emails = extract_emails(text_with_email)
76
+ self.assertIn("test@example.com", emails)
77
+ self.assertIn("support@crawler.com", emails)
78
+
79
+ def test_data_validation_tools(self):
80
+ """测试数据验证工具"""
81
+ # 测试邮箱验证
82
+ self.assertTrue(validate_email("test@example.com"))
83
+ self.assertFalse(validate_email("invalid-email"))
84
+
85
+ # 测试URL验证
86
+ self.assertTrue(validate_url("https://example.com"))
87
+ self.assertFalse(validate_url("invalid-url"))
88
+
89
+ # 测试电话验证
90
+ self.assertTrue(validate_phone("13812345678"))
91
+ self.assertFalse(validate_phone("12345"))
92
+
93
+ # 测试身份证验证
94
+ self.assertTrue(validate_chinese_id_card("110101199001011234"))
95
+ self.assertFalse(validate_chinese_id_card("invalid-id"))
96
+
97
+ # 测试日期验证
98
+ self.assertTrue(validate_date("2025-09-10"))
99
+ self.assertFalse(validate_date("invalid-date"))
100
+
101
+ # 测试数值范围验证
102
+ self.assertTrue(validate_number_range(50, 1, 100))
103
+ self.assertFalse(validate_number_range(150, 1, 100))
104
+
105
+ def test_request_handling_tools(self):
106
+ """测试请求处理工具"""
107
+ # 测试URL构建
108
+ base_url = "https://api.example.com"
109
+ path = "/v1/users"
110
+ query_params = {"page": 1, "limit": 10}
111
+ full_url = build_url(base_url, path, query_params)
112
+ self.assertIn("https://api.example.com/v1/users", full_url)
113
+ self.assertIn("page=1", full_url)
114
+ self.assertIn("limit=10", full_url)
115
+
116
+ # 测试添加查询参数
117
+ existing_url = "https://api.example.com/v1/users?page=1"
118
+ new_params = {"sort": "name"}
119
+ updated_url = add_query_params(existing_url, new_params)
120
+ self.assertIn("sort=name", updated_url)
121
+
122
+ # 测试合并请求头
123
+ base_headers = {"Content-Type": "application/json"}
124
+ additional_headers = {"Authorization": "Bearer token123"}
125
+ merged_headers = merge_headers(base_headers, additional_headers)
126
+ self.assertEqual(merged_headers["Content-Type"], "application/json")
127
+ self.assertEqual(merged_headers["Authorization"], "Bearer token123")
128
+
129
+ def test_anti_crawler_tools(self):
130
+ """测试反爬虫应对工具"""
131
+ # 测试随机User-Agent
132
+ user_agent = get_random_user_agent()
133
+ self.assertIsInstance(user_agent, str)
134
+ self.assertGreater(len(user_agent), 0)
135
+
136
+ # 测试代理轮换
137
+ proxy = rotate_proxy()
138
+ self.assertIsInstance(proxy, dict)
139
+
140
+ def test_distributed_coordinator_tools(self):
141
+ """测试分布式协调工具"""
142
+ # 测试任务ID生成
143
+ task_id = generate_task_id("https://example.com", "test_spider")
144
+ self.assertIsInstance(task_id, str)
145
+ self.assertEqual(len(task_id), 32) # MD5 hash长度
146
+
147
+ # 测试集群信息获取
148
+ cluster_info = get_cluster_info()
149
+ self.assertIsInstance(cluster_info, dict)
150
+ self.assertIn("worker_count", cluster_info)
151
+
152
+
153
+ if __name__ == '__main__':
154
+ unittest.main()
tests/tools_example.py ADDED
@@ -0,0 +1,258 @@
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ Crawlo框架工具包使用示例
5
+ """
6
+ from crawlo.tools import (
7
+ # 日期工具
8
+ parse_time,
9
+ format_time,
10
+ time_diff,
11
+
12
+ # 数据清洗工具
13
+ clean_text,
14
+ format_currency,
15
+ extract_emails,
16
+
17
+ # 数据验证工具
18
+ validate_email,
19
+ validate_url,
20
+ validate_phone,
21
+
22
+ # 请求处理工具
23
+ build_url,
24
+ add_query_params,
25
+ merge_headers,
26
+
27
+ # 反爬虫应对工具
28
+ get_random_user_agent,
29
+ rotate_proxy,
30
+
31
+ # 带认证代理工具
32
+ AuthenticatedProxy,
33
+ create_proxy_config,
34
+ get_proxy_info,
35
+
36
+ # 分布式协调工具
37
+ generate_task_id,
38
+ get_cluster_info
39
+ )
40
+
41
+
42
+ def demo_date_tools():
43
+ """演示日期工具的使用"""
44
+ print("=== 日期工具演示 ===\n")
45
+
46
+ # 解析时间
47
+ time_str = "2025-09-10 14:30:00"
48
+ parsed_time = parse_time(time_str)
49
+ print(f"解析时间: {time_str} -> {parsed_time}")
50
+
51
+ # 格式化时间
52
+ formatted_time = format_time(parsed_time, "%Y年%m月%d日 %H:%M:%S")
53
+ print(f"格式化时间: {parsed_time} -> {formatted_time}")
54
+
55
+ # 时间差计算
56
+ time_str2 = "2025-09-11 16:45:30"
57
+ parsed_time2 = parse_time(time_str2)
58
+ diff = time_diff(parsed_time2, parsed_time)
59
+ print(f"时间差: {time_str2} - {time_str} = {diff} 秒")
60
+
61
+ print()
62
+
63
+
64
+ def demo_data_cleaning_tools():
65
+ """演示数据清洗工具的使用"""
66
+ print("=== 数据清洗工具演示 ===\n")
67
+
68
+ # 清洗文本
69
+ dirty_text = "<p>这是一个&nbsp;<b>测试</b>&amp;文本</p>"
70
+ clean_result = clean_text(dirty_text)
71
+ print(f"清洗文本: {dirty_text} -> {clean_result}")
72
+
73
+ # 格式化货币
74
+ price = 1234.567
75
+ formatted_price = format_currency(price, "¥", 2)
76
+ print(f"格式化货币: {price} -> {formatted_price}")
77
+
78
+ # 提取邮箱
79
+ text_with_email = "联系邮箱: test@example.com, support@crawler.com"
80
+ emails = extract_emails(text_with_email)
81
+ print(f"提取邮箱: {text_with_email} -> {emails}")
82
+
83
+ print()
84
+
85
+
86
+ def demo_data_validation_tools():
87
+ """演示数据验证工具的使用"""
88
+ print("=== 数据验证工具演示 ===\n")
89
+
90
+ # 验证邮箱
91
+ email = "test@example.com"
92
+ is_valid_email = validate_email(email)
93
+ print(f"验证邮箱: {email} -> {'有效' if is_valid_email else '无效'}")
94
+
95
+ # 验证无效邮箱
96
+ invalid_email = "invalid-email"
97
+ is_valid_invalid = validate_email(invalid_email)
98
+ print(f"验证邮箱: {invalid_email} -> {'有效' if is_valid_invalid else '无效'}")
99
+
100
+ # 验证URL
101
+ url = "https://example.com/path?param=value"
102
+ is_valid_url = validate_url(url)
103
+ print(f"验证URL: {url} -> {'有效' if is_valid_url else '无效'}")
104
+
105
+ # 验证电话号码
106
+ phone = "13812345678"
107
+ is_valid_phone = validate_phone(phone)
108
+ print(f"验证电话: {phone} -> {'有效' if is_valid_phone else '无效'}")
109
+
110
+ print()
111
+
112
+
113
+ def demo_request_handling_tools():
114
+ """演示请求处理工具的使用"""
115
+ print("=== 请求处理工具演示 ===\n")
116
+
117
+ # 构建URL
118
+ base_url = "https://api.example.com"
119
+ path = "/v1/users"
120
+ query_params = {"page": 1, "limit": 10}
121
+ full_url = build_url(base_url, path, query_params)
122
+ print(f"构建URL: {base_url} + {path} + {query_params} -> {full_url}")
123
+
124
+ # 添加查询参数
125
+ existing_url = "https://api.example.com/v1/users?page=1"
126
+ new_params = {"sort": "name", "order": "asc"}
127
+ updated_url = add_query_params(existing_url, new_params)
128
+ print(f"添加参数: {existing_url} + {new_params} -> {updated_url}")
129
+
130
+ # 合并请求头
131
+ base_headers = {"Content-Type": "application/json", "Accept": "application/json"}
132
+ additional_headers = {"Authorization": "Bearer token123", "User-Agent": "Crawlo/1.0"}
133
+ merged_headers = merge_headers(base_headers, additional_headers)
134
+ print(f"合并请求头:")
135
+ print(f" 基础头: {base_headers}")
136
+ print(f" 额外头: {additional_headers}")
137
+ print(f" 合并后: {merged_headers}")
138
+
139
+ print()
140
+
141
+
142
+ def demo_anti_crawler_tools():
143
+ """演示反爬虫应对工具的使用"""
144
+ print("=== 反爬虫应对工具演示 ===\n")
145
+
146
+ # 获取随机User-Agent
147
+ user_agent = get_random_user_agent()
148
+ print(f"随机User-Agent: {user_agent[:50]}...")
149
+
150
+ # 轮换代理
151
+ proxy = rotate_proxy()
152
+ print(f"轮换代理: {proxy}")
153
+
154
+ print()
155
+
156
+
157
+ def demo_authenticated_proxy_tools():
158
+ """演示带认证代理工具的使用"""
159
+ print("=== 带认证代理工具演示 ===\n")
160
+
161
+ # 创建带认证的代理
162
+ proxy_url = "http://username:password@proxy.example.com:8080"
163
+ proxy = AuthenticatedProxy(proxy_url)
164
+
165
+ print(f"代理URL: {proxy}")
166
+ print(f"清洁URL: {proxy.clean_url}")
167
+ print(f"用户名: {proxy.username}")
168
+ print(f"密码: {proxy.password}")
169
+ print(f"代理字典: {proxy.proxy_dict}")
170
+ print(f"认证凭据: {proxy.get_auth_credentials()}")
171
+ print(f"认证头: {proxy.get_auth_header()}")
172
+ print(f"是否有效: {proxy.is_valid()}")
173
+
174
+ # 创建代理配置
175
+ proxy_config = create_proxy_config(proxy_url)
176
+ print(f"\n代理配置: {proxy_config}")
177
+
178
+ # 获取代理信息
179
+ proxy_info = get_proxy_info(proxy_url)
180
+ print(f"代理信息: {proxy_info}")
181
+
182
+ print()
183
+
184
+
185
+ def demo_distributed_coordinator_tools():
186
+ """演示分布式协调工具的使用"""
187
+ print("=== 分布式协调工具演示 ===\n")
188
+
189
+ # 生成任务ID
190
+ url = "https://example.com/page/1"
191
+ spider_name = "example_spider"
192
+ task_id = generate_task_id(url, spider_name)
193
+ print(f"生成任务ID: URL={url}, Spider={spider_name} -> {task_id}")
194
+
195
+ # 获取集群信息
196
+ cluster_info = get_cluster_info()
197
+ print(f"集群信息: {cluster_info}")
198
+
199
+ print()
200
+
201
+
202
+ if __name__ == '__main__':
203
+ # 运行演示
204
+ demo_date_tools()
205
+ demo_data_cleaning_tools()
206
+ demo_data_validation_tools()
207
+ demo_request_handling_tools()
208
+ demo_anti_crawler_tools()
209
+ demo_authenticated_proxy_tools()
210
+ demo_distributed_coordinator_tools()
211
+
212
+ print("=== 在爬虫中使用工具包 ===\n")
213
+ print("在爬虫项目中,您可以这样使用工具包:")
214
+ print("""
215
+ from crawlo import Spider, Request
216
+ from crawlo.tools import (
217
+ clean_text,
218
+ validate_email,
219
+ get_random_user_agent,
220
+ build_url,
221
+ AuthenticatedProxy
222
+ )
223
+
224
+ class ExampleSpider(Spider):
225
+ def start_requests(self):
226
+ headers = {"User-Agent": get_random_user_agent()}
227
+
228
+ # 使用带认证的代理
229
+ proxy_url = "http://username:password@proxy.example.com:8080"
230
+ proxy = AuthenticatedProxy(proxy_url)
231
+
232
+ request = Request("https://example.com", headers=headers)
233
+ # 根据下载器类型设置代理
234
+ downloader_type = self.crawler.settings.get("DOWNLOADER_TYPE", "aiohttp")
235
+ if downloader_type == "aiohttp":
236
+ request.proxy = proxy.clean_url
237
+ auth = proxy.get_auth_credentials()
238
+ if auth:
239
+ request.meta["proxy_auth"] = auth
240
+ else:
241
+ request.proxy = proxy.proxy_dict
242
+
243
+ yield request
244
+
245
+ def parse(self, response):
246
+ # 提取数据
247
+ title = response.css('h1::text').get()
248
+ email = response.css('.email::text').get()
249
+
250
+ # 清洗和验证数据
251
+ clean_title = clean_text(title) if title else None
252
+ is_valid_email = validate_email(email) if email else False
253
+
254
+ # 构建下一页URL
255
+ next_page_url = build_url("https://example.com", "/page/2")
256
+
257
+ # 处理数据...
258
+ """)
@@ -1,190 +0,0 @@
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
- }