crawlo 1.1.4__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 (186) hide show
  1. crawlo/__init__.py +61 -34
  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/cli.py +40 -40
  8. crawlo/commands/__init__.py +13 -13
  9. crawlo/commands/check.py +594 -594
  10. crawlo/commands/genspider.py +151 -151
  11. crawlo/commands/list.py +155 -155
  12. crawlo/commands/run.py +285 -285
  13. crawlo/commands/startproject.py +300 -196
  14. crawlo/commands/stats.py +188 -188
  15. crawlo/commands/utils.py +186 -186
  16. crawlo/config.py +309 -279
  17. crawlo/config_validator.py +253 -0
  18. crawlo/core/__init__.py +2 -2
  19. crawlo/core/engine.py +346 -172
  20. crawlo/core/processor.py +40 -40
  21. crawlo/core/scheduler.py +137 -166
  22. crawlo/crawler.py +1027 -1027
  23. crawlo/downloader/__init__.py +266 -242
  24. crawlo/downloader/aiohttp_downloader.py +220 -212
  25. crawlo/downloader/cffi_downloader.py +256 -251
  26. crawlo/downloader/httpx_downloader.py +259 -259
  27. crawlo/downloader/hybrid_downloader.py +214 -0
  28. crawlo/downloader/playwright_downloader.py +403 -0
  29. crawlo/downloader/selenium_downloader.py +473 -0
  30. crawlo/event.py +11 -11
  31. crawlo/exceptions.py +81 -81
  32. crawlo/extension/__init__.py +37 -37
  33. crawlo/extension/health_check.py +141 -141
  34. crawlo/extension/log_interval.py +57 -57
  35. crawlo/extension/log_stats.py +81 -81
  36. crawlo/extension/logging_extension.py +43 -43
  37. crawlo/extension/memory_monitor.py +104 -88
  38. crawlo/extension/performance_profiler.py +133 -117
  39. crawlo/extension/request_recorder.py +107 -107
  40. crawlo/filters/__init__.py +154 -154
  41. crawlo/filters/aioredis_filter.py +280 -242
  42. crawlo/filters/memory_filter.py +269 -269
  43. crawlo/items/__init__.py +23 -23
  44. crawlo/items/base.py +21 -21
  45. crawlo/items/fields.py +53 -53
  46. crawlo/items/items.py +104 -104
  47. crawlo/middleware/__init__.py +21 -21
  48. crawlo/middleware/default_header.py +32 -32
  49. crawlo/middleware/download_delay.py +28 -28
  50. crawlo/middleware/middleware_manager.py +135 -135
  51. crawlo/middleware/proxy.py +272 -248
  52. crawlo/middleware/request_ignore.py +30 -30
  53. crawlo/middleware/response_code.py +18 -18
  54. crawlo/middleware/response_filter.py +26 -26
  55. crawlo/middleware/retry.py +124 -124
  56. crawlo/mode_manager.py +206 -201
  57. crawlo/network/__init__.py +21 -21
  58. crawlo/network/request.py +338 -311
  59. crawlo/network/response.py +360 -271
  60. crawlo/pipelines/__init__.py +21 -21
  61. crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
  62. crawlo/pipelines/console_pipeline.py +39 -39
  63. crawlo/pipelines/csv_pipeline.py +316 -316
  64. crawlo/pipelines/database_dedup_pipeline.py +224 -224
  65. crawlo/pipelines/json_pipeline.py +218 -218
  66. crawlo/pipelines/memory_dedup_pipeline.py +115 -115
  67. crawlo/pipelines/mongo_pipeline.py +131 -131
  68. crawlo/pipelines/mysql_pipeline.py +316 -316
  69. crawlo/pipelines/pipeline_manager.py +56 -56
  70. crawlo/pipelines/redis_dedup_pipeline.py +166 -162
  71. crawlo/project.py +153 -153
  72. crawlo/queue/pqueue.py +37 -37
  73. crawlo/queue/queue_manager.py +320 -307
  74. crawlo/queue/redis_priority_queue.py +277 -209
  75. crawlo/settings/__init__.py +7 -7
  76. crawlo/settings/default_settings.py +216 -278
  77. crawlo/settings/setting_manager.py +99 -99
  78. crawlo/spider/__init__.py +639 -639
  79. crawlo/stats_collector.py +59 -59
  80. crawlo/subscriber.py +130 -130
  81. crawlo/task_manager.py +30 -30
  82. crawlo/templates/crawlo.cfg.tmpl +10 -10
  83. crawlo/templates/project/__init__.py.tmpl +3 -3
  84. crawlo/templates/project/items.py.tmpl +17 -17
  85. crawlo/templates/project/middlewares.py.tmpl +110 -110
  86. crawlo/templates/project/pipelines.py.tmpl +97 -97
  87. crawlo/templates/project/run.py.tmpl +251 -251
  88. crawlo/templates/project/settings.py.tmpl +326 -279
  89. crawlo/templates/project/settings_distributed.py.tmpl +120 -0
  90. crawlo/templates/project/settings_gentle.py.tmpl +95 -0
  91. crawlo/templates/project/settings_high_performance.py.tmpl +152 -0
  92. crawlo/templates/project/settings_simple.py.tmpl +69 -0
  93. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  94. crawlo/templates/spider/spider.py.tmpl +141 -141
  95. crawlo/tools/__init__.py +183 -0
  96. crawlo/tools/anti_crawler.py +269 -0
  97. crawlo/tools/authenticated_proxy.py +241 -0
  98. crawlo/tools/data_validator.py +181 -0
  99. crawlo/tools/date_tools.py +36 -0
  100. crawlo/tools/distributed_coordinator.py +387 -0
  101. crawlo/tools/retry_mechanism.py +221 -0
  102. crawlo/tools/scenario_adapter.py +263 -0
  103. crawlo/utils/__init__.py +35 -7
  104. crawlo/utils/batch_processor.py +261 -0
  105. crawlo/utils/controlled_spider_mixin.py +439 -439
  106. crawlo/utils/date_tools.py +290 -233
  107. crawlo/utils/db_helper.py +343 -343
  108. crawlo/utils/enhanced_error_handler.py +360 -0
  109. crawlo/utils/env_config.py +106 -0
  110. crawlo/utils/error_handler.py +126 -0
  111. crawlo/utils/func_tools.py +82 -82
  112. crawlo/utils/large_scale_config.py +286 -286
  113. crawlo/utils/large_scale_helper.py +343 -343
  114. crawlo/utils/log.py +128 -128
  115. crawlo/utils/performance_monitor.py +285 -0
  116. crawlo/utils/queue_helper.py +175 -175
  117. crawlo/utils/redis_connection_pool.py +335 -0
  118. crawlo/utils/redis_key_validator.py +200 -0
  119. crawlo/utils/request.py +267 -267
  120. crawlo/utils/request_serializer.py +219 -219
  121. crawlo/utils/spider_loader.py +62 -62
  122. crawlo/utils/system.py +11 -11
  123. crawlo/utils/tools.py +4 -4
  124. crawlo/utils/url.py +39 -39
  125. {crawlo-1.1.4.dist-info → crawlo-1.1.5.dist-info}/METADATA +401 -403
  126. crawlo-1.1.5.dist-info/RECORD +185 -0
  127. examples/__init__.py +7 -7
  128. tests/__init__.py +7 -7
  129. tests/advanced_tools_example.py +276 -0
  130. tests/authenticated_proxy_example.py +237 -0
  131. tests/cleaners_example.py +161 -0
  132. tests/config_validation_demo.py +103 -0
  133. {examples → tests}/controlled_spider_example.py +205 -205
  134. tests/date_tools_example.py +181 -0
  135. tests/dynamic_loading_example.py +524 -0
  136. tests/dynamic_loading_test.py +105 -0
  137. tests/env_config_example.py +134 -0
  138. tests/error_handling_example.py +172 -0
  139. tests/redis_key_validation_demo.py +131 -0
  140. tests/response_improvements_example.py +145 -0
  141. tests/test_advanced_tools.py +149 -0
  142. tests/test_all_redis_key_configs.py +146 -0
  143. tests/test_authenticated_proxy.py +142 -0
  144. tests/test_cleaners.py +55 -0
  145. tests/test_comprehensive.py +147 -0
  146. tests/test_config_validator.py +194 -0
  147. tests/test_date_tools.py +124 -0
  148. tests/test_dynamic_downloaders_proxy.py +125 -0
  149. tests/test_dynamic_proxy.py +93 -0
  150. tests/test_dynamic_proxy_config.py +147 -0
  151. tests/test_dynamic_proxy_real.py +110 -0
  152. tests/test_edge_cases.py +304 -0
  153. tests/test_enhanced_error_handler.py +271 -0
  154. tests/test_env_config.py +122 -0
  155. tests/test_error_handler_compatibility.py +113 -0
  156. tests/test_final_validation.py +153 -153
  157. tests/test_framework_env_usage.py +104 -0
  158. tests/test_integration.py +357 -0
  159. tests/test_item_dedup_redis_key.py +123 -0
  160. tests/test_parsel.py +30 -0
  161. tests/test_performance.py +328 -0
  162. tests/test_proxy_health_check.py +32 -32
  163. tests/test_proxy_middleware_integration.py +136 -136
  164. tests/test_proxy_providers.py +56 -56
  165. tests/test_proxy_stats.py +19 -19
  166. tests/test_proxy_strategies.py +59 -59
  167. tests/test_queue_manager_redis_key.py +177 -0
  168. tests/test_redis_config.py +28 -28
  169. tests/test_redis_connection_pool.py +295 -0
  170. tests/test_redis_key_naming.py +182 -0
  171. tests/test_redis_key_validator.py +124 -0
  172. tests/test_redis_queue.py +224 -224
  173. tests/test_request_serialization.py +70 -70
  174. tests/test_response_improvements.py +153 -0
  175. tests/test_scheduler.py +241 -241
  176. tests/test_simple_response.py +62 -0
  177. tests/test_telecom_spider_redis_key.py +206 -0
  178. tests/test_template_content.py +88 -0
  179. tests/test_template_redis_key.py +135 -0
  180. tests/test_tools.py +154 -0
  181. tests/tools_example.py +258 -0
  182. crawlo/core/enhanced_engine.py +0 -190
  183. crawlo-1.1.4.dist-info/RECORD +0 -117
  184. {crawlo-1.1.4.dist-info → crawlo-1.1.5.dist-info}/WHEEL +0 -0
  185. {crawlo-1.1.4.dist-info → crawlo-1.1.5.dist-info}/entry_points.txt +0 -0
  186. {crawlo-1.1.4.dist-info → crawlo-1.1.5.dist-info}/top_level.txt +0 -0
crawlo/network/request.py CHANGED
@@ -1,312 +1,339 @@
1
- #!/usr/bin/python
2
- # -*- coding: UTF-8 -*-
3
- """
4
- HTTP Request 封装模块
5
- ====================
6
- 提供功能完善的HTTP请求封装,支持:
7
- - JSON/表单数据自动处理
8
- - 优先级排序机制
9
- - 安全的深拷贝操作
10
- - 灵活的请求配置
11
- """
12
- import json
13
- from copy import deepcopy
14
- from urllib.parse import urlencode
15
- from w3lib.url import safe_url_string
16
- from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
17
-
18
- from crawlo.utils.url import escape_ajax
19
-
20
-
21
- _Request = TypeVar("_Request", bound="Request")
22
-
23
-
24
- class RequestPriority:
25
- """请求优先级常量和工具类"""
26
- URGENT = -200 # 紧急任务
27
- HIGH = -100 # 高优先级
28
- NORMAL = 0 # 正常优先级(默认)
29
- LOW = 100 # 低优先级
30
- BACKGROUND = 200 # 后台任务
31
-
32
- @classmethod
33
- def get_all_priorities(cls) -> Dict[str, int]:
34
- """获取所有优先级常量"""
35
- return {
36
- 'URGENT': cls.URGENT,
37
- 'HIGH': cls.HIGH,
38
- 'NORMAL': cls.NORMAL,
39
- 'LOW': cls.LOW,
40
- 'BACKGROUND': cls.BACKGROUND
41
- }
42
-
43
- @classmethod
44
- def from_string(cls, priority_str: str) -> int:
45
- """从字符串获取优先级值"""
46
- priorities = cls.get_all_priorities()
47
- if priority_str.upper() not in priorities:
48
- raise ValueError(f"不支持的优先级: {priority_str}, 支持: {list(priorities.keys())}")
49
- return priorities[priority_str.upper()]
50
-
51
-
52
- class Request:
53
- """
54
- 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
55
- 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
56
- 不支持文件上传(multipart/form-data),保持轻量。
57
- """
58
-
59
- __slots__ = (
60
- '_url',
61
- '_meta',
62
- 'callback',
63
- 'cb_kwargs',
64
- 'err_back',
65
- 'headers',
66
- 'body',
67
- 'method',
68
- 'cookies',
69
- 'priority',
70
- 'encoding',
71
- 'dont_filter',
72
- 'timeout',
73
- 'proxy',
74
- 'allow_redirects',
75
- 'auth',
76
- 'verify',
77
- 'flags',
78
- '_json_body',
79
- '_form_data'
80
- )
81
-
82
- def __init__(
83
- self,
84
- url: str,
85
- callback: Optional[Callable] = None,
86
- method: Optional[str] = 'GET',
87
- headers: Optional[Dict[str, str]] = None,
88
- body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
89
- form_data: Optional[Dict[Any, Any]] = None,
90
- json_body: Optional[Dict[Any, Any]] = None,
91
- cb_kwargs: Optional[Dict[str, Any]] = None,
92
- cookies: Optional[Dict[str, str]] = None,
93
- meta: Optional[Dict[str, Any]] = None,
94
- priority: int = RequestPriority.NORMAL,
95
- dont_filter: bool = False,
96
- timeout: Optional[float] = None,
97
- proxy: Optional[str] = None,
98
- allow_redirects: bool = True,
99
- auth: Optional[tuple] = None,
100
- verify: bool = True,
101
- flags: Optional[List[str]] = None,
102
- encoding: str = 'utf-8'
103
- ):
104
- """
105
- 初始化请求对象。
106
-
107
- :param url: 请求 URL(必须)
108
- :param callback: 成功回调函数
109
- :param method: HTTP 方法,默认 GET
110
- :param headers: 请求头
111
- :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
112
- :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
113
- :param json_body: JSON 数据,自动序列化并设置 Content-Type
114
- :param cb_kwargs: 传递给 callback 的额外参数
115
- :param cookies: Cookies 字典
116
- :param meta: 元数据(跨中间件传递数据)
117
- :param priority: 优先级(数值越小越优先)
118
- :param dont_filter: 是否跳过去重
119
- :param timeout: 超时时间(秒)
120
- :param proxy: 代理地址,如 http://127.0.0.1:8080
121
- :param allow_redirects: 是否允许重定向
122
- :param auth: 认证元组 (username, password)
123
- :param verify: 是否验证 SSL 证书
124
- :param flags: 标记(用于调试或分类)
125
- :param encoding: 字符编码,默认 utf-8
126
- """
127
- self.callback = callback
128
- self.method = str(method).upper()
129
- self.headers = headers or {}
130
- self.cookies = cookies or {}
131
- self.priority = -priority # 用于排序:值越小优先级越高
132
-
133
- # 🔧 安全处理 meta,移除 logger 后再 deepcopy
134
- self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
135
-
136
- self.timeout = self._meta.get('download_timeout', timeout)
137
- self.proxy = proxy
138
- self.allow_redirects = allow_redirects
139
- self.auth = auth
140
- self.verify = verify
141
- self.flags = flags or []
142
- self.encoding = encoding
143
- self.cb_kwargs = cb_kwargs or {}
144
- self.body = body
145
- # 保存高层语义参数(用于 copy)
146
- self._json_body = json_body
147
- self._form_data = form_data
148
-
149
- # 构建 body
150
- if json_body is not None:
151
- if 'Content-Type' not in self.headers:
152
- self.headers['Content-Type'] = 'application/json'
153
- self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
154
- if self.method == 'GET':
155
- self.method = 'POST'
156
-
157
- elif form_data is not None:
158
- if self.method == 'GET':
159
- self.method = 'POST'
160
- if 'Content-Type' not in self.headers:
161
- self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
162
- query_str = urlencode(form_data)
163
- self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
164
-
165
-
166
- else:
167
- # 处理原始 body
168
- if isinstance(self.body, dict):
169
- if 'Content-Type' not in self.headers:
170
- self.headers['Content-Type'] = 'application/json'
171
- self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
172
- elif isinstance(self.body, str):
173
- self.body = self.body.encode(encoding)
174
-
175
- self.dont_filter = dont_filter
176
- self._set_url(url)
177
-
178
- @staticmethod
179
- def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
180
- """安全地 deepcopy meta,移除 logger 后再复制"""
181
- import logging
182
-
183
- def clean_logger_recursive(obj):
184
- """递归移除 logger 对象"""
185
- if isinstance(obj, logging.Logger):
186
- return None
187
- elif isinstance(obj, dict):
188
- cleaned = {}
189
- for k, v in obj.items():
190
- if not (k == 'logger' or isinstance(v, logging.Logger)):
191
- cleaned[k] = clean_logger_recursive(v)
192
- return cleaned
193
- elif isinstance(obj, (list, tuple)):
194
- cleaned_list = []
195
- for item in obj:
196
- cleaned_item = clean_logger_recursive(item)
197
- if cleaned_item is not None:
198
- cleaned_list.append(cleaned_item)
199
- return type(obj)(cleaned_list)
200
- else:
201
- return obj
202
-
203
- # 先清理 logger,再 deepcopy
204
- cleaned_meta = clean_logger_recursive(meta)
205
- return deepcopy(cleaned_meta)
206
-
207
- def copy(self: _Request) -> _Request:
208
- """
209
- 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
210
- """
211
- return type(self)(
212
- url=self.url,
213
- callback=self.callback,
214
- method=self.method,
215
- headers=self.headers.copy(),
216
- body=None, # form_data/json_body 重新生成
217
- form_data=self._form_data,
218
- json_body=self._json_body,
219
- cb_kwargs=deepcopy(self.cb_kwargs),
220
- err_back=self.err_back,
221
- cookies=self.cookies.copy(),
222
- meta=deepcopy(self._meta),
223
- priority=-self.priority,
224
- dont_filter=self.dont_filter,
225
- timeout=self.timeout,
226
- proxy=self.proxy,
227
- allow_redirects=self.allow_redirects,
228
- auth=self.auth,
229
- verify=self.verify,
230
- flags=self.flags.copy(),
231
- encoding=self.encoding
232
- )
233
-
234
- def set_meta(self, key: str, value: Any) -> 'Request':
235
- """设置 meta 中的某个键值,支持链式调用。"""
236
- self._meta[key] = value
237
- return self
238
-
239
- def add_header(self, key: str, value: str) -> 'Request':
240
- """添加请求头,支持链式调用。"""
241
- self.headers[key] = value
242
- return self
243
-
244
- def add_headers(self, headers: Dict[str, str]) -> 'Request':
245
- """批量添加请求头,支持链式调用。"""
246
- self.headers.update(headers)
247
- return self
248
-
249
- def set_proxy(self, proxy: str) -> 'Request':
250
- """设置代理,支持链式调用。"""
251
- self.proxy = proxy
252
- return self
253
-
254
- def set_timeout(self, timeout: float) -> 'Request':
255
- """设置超时时间,支持链式调用。"""
256
- self.timeout = timeout
257
- return self
258
-
259
- def add_flag(self, flag: str) -> 'Request':
260
- """添加标记,支持链式调用。"""
261
- if flag not in self.flags:
262
- self.flags.append(flag)
263
- return self
264
-
265
- def remove_flag(self, flag: str) -> 'Request':
266
- """移除标记,支持链式调用。"""
267
- if flag in self.flags:
268
- self.flags.remove(flag)
269
- return self
270
-
271
- def _set_url(self, url: str) -> None:
272
- """安全设置 URL,确保格式正确。"""
273
- if not isinstance(url, str):
274
- raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
275
-
276
- if not url.strip():
277
- raise ValueError("URL 不能为空")
278
-
279
- # 检查危险的 URL scheme
280
- dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
281
- if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
282
- raise ValueError(f"URL scheme 不安全: {url[:20]}...")
283
-
284
- s = safe_url_string(url, self.encoding)
285
- escaped_url = escape_ajax(s)
286
-
287
- if not escaped_url.startswith(('http://', 'https://')):
288
- raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
289
-
290
- # 检查 URL 长度
291
- if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
292
- raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
293
-
294
- self._url = escaped_url
295
-
296
- @property
297
- def url(self) -> str:
298
- return self._url
299
-
300
- @property
301
- def meta(self) -> Dict[str, Any]:
302
- return self._meta
303
-
304
- def __str__(self) -> str:
305
- return f'<Request url={self.url} method={self.method}>'
306
-
307
- def __repr__(self) -> str:
308
- return str(self)
309
-
310
- def __lt__(self, other: _Request) -> bool:
311
- """用于按优先级排序"""
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ HTTP Request 封装模块
5
+ ====================
6
+ 提供功能完善的HTTP请求封装,支持:
7
+ - JSON/表单数据自动处理
8
+ - 优先级排序机制
9
+ - 安全的深拷贝操作
10
+ - 灵活的请求配置
11
+ """
12
+ import json
13
+ from copy import deepcopy
14
+ from urllib.parse import urlencode
15
+ from w3lib.url import safe_url_string
16
+ from typing import Dict, Optional, Callable, Union, Any, TypeVar, List
17
+
18
+ from crawlo.utils.url import escape_ajax
19
+
20
+
21
+ _Request = TypeVar("_Request", bound="Request")
22
+
23
+
24
+ class RequestPriority:
25
+ """请求优先级常量和工具类"""
26
+ URGENT = -200 # 紧急任务
27
+ HIGH = -100 # 高优先级
28
+ NORMAL = 0 # 正常优先级(默认)
29
+ LOW = 100 # 低优先级
30
+ BACKGROUND = 200 # 后台任务
31
+
32
+ @classmethod
33
+ def get_all_priorities(cls) -> Dict[str, int]:
34
+ """获取所有优先级常量"""
35
+ return {
36
+ 'URGENT': cls.URGENT,
37
+ 'HIGH': cls.HIGH,
38
+ 'NORMAL': cls.NORMAL,
39
+ 'LOW': cls.LOW,
40
+ 'BACKGROUND': cls.BACKGROUND
41
+ }
42
+
43
+ @classmethod
44
+ def from_string(cls, priority_str: str) -> int:
45
+ """从字符串获取优先级值"""
46
+ priorities = cls.get_all_priorities()
47
+ if priority_str.upper() not in priorities:
48
+ raise ValueError(f"不支持的优先级: {priority_str}, 支持: {list(priorities.keys())}")
49
+ return priorities[priority_str.upper()]
50
+
51
+
52
+ class Request:
53
+ """
54
+ 封装一个 HTTP 请求对象,用于爬虫框架中表示一个待抓取的请求任务。
55
+ 支持 JSON、表单、原始 body 提交,自动处理 Content-Type 与编码。
56
+ 不支持文件上传(multipart/form-data),保持轻量。
57
+ """
58
+
59
+ __slots__ = (
60
+ '_url',
61
+ '_meta',
62
+ 'callback',
63
+ 'cb_kwargs',
64
+ 'err_back',
65
+ 'headers',
66
+ 'body',
67
+ 'method',
68
+ 'cookies',
69
+ 'priority',
70
+ 'encoding',
71
+ 'dont_filter',
72
+ 'timeout',
73
+ 'proxy',
74
+ 'allow_redirects',
75
+ 'auth',
76
+ 'verify',
77
+ 'flags',
78
+ '_json_body',
79
+ '_form_data',
80
+ 'use_dynamic_loader',
81
+ 'dynamic_loader_options'
82
+ )
83
+
84
+ def __init__(
85
+ self,
86
+ url: str,
87
+ callback: Optional[Callable] = None,
88
+ method: Optional[str] = 'GET',
89
+ headers: Optional[Dict[str, str]] = None,
90
+ body: Optional[Union[bytes, str, Dict[Any, Any]]] = None,
91
+ form_data: Optional[Dict[Any, Any]] = None,
92
+ json_body: Optional[Dict[Any, Any]] = None,
93
+ cb_kwargs: Optional[Dict[str, Any]] = None,
94
+ cookies: Optional[Dict[str, str]] = None,
95
+ meta: Optional[Dict[str, Any]] = None,
96
+ priority: int = RequestPriority.NORMAL,
97
+ dont_filter: bool = False,
98
+ timeout: Optional[float] = None,
99
+ proxy: Optional[str] = None,
100
+ allow_redirects: bool = True,
101
+ auth: Optional[tuple] = None,
102
+ verify: bool = True,
103
+ flags: Optional[List[str]] = None,
104
+ encoding: str = 'utf-8',
105
+ # 动态加载相关参数
106
+ use_dynamic_loader: bool = False,
107
+ dynamic_loader_options: Optional[Dict[str, Any]] = None
108
+ ):
109
+ """
110
+ 初始化请求对象。
111
+
112
+ :param url: 请求 URL(必须)
113
+ :param callback: 成功回调函数
114
+ :param method: HTTP 方法,默认 GET
115
+ :param headers: 请求头
116
+ :param body: 原始请求体(bytes/str),若为 dict 且未使用 json_body/form_data,则自动转为 JSON
117
+ :param form_data: 表单数据,自动转为 application/x-www-form-urlencoded
118
+ :param json_body: JSON 数据,自动序列化并设置 Content-Type
119
+ :param cb_kwargs: 传递给 callback 的额外参数
120
+ :param cookies: Cookies 字典
121
+ :param meta: 元数据(跨中间件传递数据)
122
+ :param priority: 优先级(数值越小越优先)
123
+ :param dont_filter: 是否跳过去重
124
+ :param timeout: 超时时间(秒)
125
+ :param proxy: 代理地址,如 http://127.0.0.1:8080
126
+ :param allow_redirects: 是否允许重定向
127
+ :param auth: 认证元组 (username, password)
128
+ :param verify: 是否验证 SSL 证书
129
+ :param flags: 标记(用于调试或分类)
130
+ :param encoding: 字符编码,默认 utf-8
131
+ """
132
+ self.callback = callback
133
+ self.method = str(method).upper()
134
+ self.headers = headers or {}
135
+ self.cookies = cookies or {}
136
+ self.priority = -priority # 用于排序:值越小优先级越高
137
+
138
+ # 🔧 安全处理 meta,移除 logger 后再 deepcopy
139
+ self._meta = self._safe_deepcopy_meta(meta) if meta is not None else {}
140
+
141
+ self.timeout = self._meta.get('download_timeout', timeout)
142
+ self.proxy = proxy
143
+ self.allow_redirects = allow_redirects
144
+ self.auth = auth
145
+ self.verify = verify
146
+ self.flags = flags or []
147
+ self.encoding = encoding
148
+ self.cb_kwargs = cb_kwargs or {}
149
+ self.body = body
150
+ # 保存高层语义参数(用于 copy)
151
+ self._json_body = json_body
152
+ self._form_data = form_data
153
+
154
+ # 动态加载相关属性
155
+ self.use_dynamic_loader = use_dynamic_loader
156
+ self.dynamic_loader_options = dynamic_loader_options or {}
157
+
158
+ # 构建 body
159
+ if json_body is not None:
160
+ if 'Content-Type' not in self.headers:
161
+ self.headers['Content-Type'] = 'application/json'
162
+ self.body = json.dumps(json_body, ensure_ascii=False).encode(encoding)
163
+ if self.method == 'GET':
164
+ self.method = 'POST'
165
+
166
+ elif form_data is not None:
167
+ if self.method == 'GET':
168
+ self.method = 'POST'
169
+ if 'Content-Type' not in self.headers:
170
+ self.headers['Content-Type'] = 'application/x-www-form-urlencoded'
171
+ query_str = urlencode(form_data)
172
+ self.body = query_str.encode(encoding) # ✅ 显式编码为 bytes
173
+
174
+
175
+ else:
176
+ # 处理原始 body
177
+ if isinstance(self.body, dict):
178
+ if 'Content-Type' not in self.headers:
179
+ self.headers['Content-Type'] = 'application/json'
180
+ self.body = json.dumps(self.body, ensure_ascii=False).encode(encoding)
181
+ elif isinstance(self.body, str):
182
+ self.body = self.body.encode(encoding)
183
+
184
+ self.dont_filter = dont_filter
185
+ self._set_url(url)
186
+
187
+ @staticmethod
188
+ def _safe_deepcopy_meta(meta: Dict[str, Any]) -> Dict[str, Any]:
189
+ """安全地 deepcopy meta,移除 logger 后再复制"""
190
+ import logging
191
+
192
+ def clean_logger_recursive(obj):
193
+ """递归移除 logger 对象"""
194
+ if isinstance(obj, logging.Logger):
195
+ return None
196
+ elif isinstance(obj, dict):
197
+ cleaned = {}
198
+ for k, v in obj.items():
199
+ if not (k == 'logger' or isinstance(v, logging.Logger)):
200
+ cleaned[k] = clean_logger_recursive(v)
201
+ return cleaned
202
+ elif isinstance(obj, (list, tuple)):
203
+ cleaned_list = []
204
+ for item in obj:
205
+ cleaned_item = clean_logger_recursive(item)
206
+ if cleaned_item is not None:
207
+ cleaned_list.append(cleaned_item)
208
+ return type(obj)(cleaned_list)
209
+ else:
210
+ return obj
211
+
212
+ # 先清理 logger,再 deepcopy
213
+ cleaned_meta = clean_logger_recursive(meta)
214
+ return deepcopy(cleaned_meta)
215
+
216
+ def copy(self: _Request) -> _Request:
217
+ """
218
+ 创建当前请求的副本,保留所有高层语义(json_body/form_data)。
219
+ """
220
+ return type(self)(
221
+ url=self.url,
222
+ callback=self.callback,
223
+ method=self.method,
224
+ headers=self.headers.copy(),
225
+ body=None, # 由 form_data/json_body 重新生成
226
+ form_data=self._form_data,
227
+ json_body=self._json_body,
228
+ cb_kwargs=deepcopy(self.cb_kwargs),
229
+ err_back=self.err_back,
230
+ cookies=self.cookies.copy(),
231
+ meta=deepcopy(self._meta),
232
+ priority=-self.priority,
233
+ dont_filter=self.dont_filter,
234
+ timeout=self.timeout,
235
+ proxy=self.proxy,
236
+ allow_redirects=self.allow_redirects,
237
+ auth=self.auth,
238
+ verify=self.verify,
239
+ flags=self.flags.copy(),
240
+ encoding=self.encoding,
241
+ use_dynamic_loader=self.use_dynamic_loader,
242
+ dynamic_loader_options=deepcopy(self.dynamic_loader_options)
243
+ )
244
+
245
+ def set_meta(self, key: str, value: Any) -> 'Request':
246
+ """设置 meta 中的某个键值,支持链式调用。"""
247
+ self._meta[key] = value
248
+ return self
249
+
250
+ def add_header(self, key: str, value: str) -> 'Request':
251
+ """添加请求头,支持链式调用。"""
252
+ self.headers[key] = value
253
+ return self
254
+
255
+ def add_headers(self, headers: Dict[str, str]) -> 'Request':
256
+ """批量添加请求头,支持链式调用。"""
257
+ self.headers.update(headers)
258
+ return self
259
+
260
+ def set_proxy(self, proxy: str) -> 'Request':
261
+ """设置代理,支持链式调用。"""
262
+ self.proxy = proxy
263
+ return self
264
+
265
+ def set_timeout(self, timeout: float) -> 'Request':
266
+ """设置超时时间,支持链式调用。"""
267
+ self.timeout = timeout
268
+ return self
269
+
270
+ def add_flag(self, flag: str) -> 'Request':
271
+ """添加标记,支持链式调用。"""
272
+ if flag not in self.flags:
273
+ self.flags.append(flag)
274
+ return self
275
+
276
+ def remove_flag(self, flag: str) -> 'Request':
277
+ """移除标记,支持链式调用。"""
278
+ if flag in self.flags:
279
+ self.flags.remove(flag)
280
+ return self
281
+
282
+ def set_dynamic_loader(self, use_dynamic: bool = True, options: Optional[Dict[str, Any]] = None) -> 'Request':
283
+ """设置使用动态加载器,支持链式调用。"""
284
+ self.use_dynamic_loader = use_dynamic
285
+ if options:
286
+ self.dynamic_loader_options = options
287
+ # 同时在meta中设置标记,供混合下载器使用
288
+ self._meta['use_dynamic_loader'] = use_dynamic
289
+ return self
290
+
291
+ def set_protocol_loader(self) -> 'Request':
292
+ """强制使用协议加载器,支持链式调用。"""
293
+ self.use_dynamic_loader = False
294
+ self._meta['use_dynamic_loader'] = False
295
+ self._meta['use_protocol_loader'] = True
296
+ return self
297
+
298
+ def _set_url(self, url: str) -> None:
299
+ """安全设置 URL,确保格式正确。"""
300
+ if not isinstance(url, str):
301
+ raise TypeError(f"Request url 必须为字符串,当前类型: {type(url).__name__}")
302
+
303
+ if not url.strip():
304
+ raise ValueError("URL 不能为空")
305
+
306
+ # 检查危险的 URL scheme
307
+ dangerous_schemes = ['file://', 'ftp://', 'javascript:', 'data:']
308
+ if any(url.lower().startswith(scheme) for scheme in dangerous_schemes):
309
+ raise ValueError(f"URL scheme 不安全: {url[:20]}...")
310
+
311
+ s = safe_url_string(url, self.encoding)
312
+ escaped_url = escape_ajax(s)
313
+
314
+ if not escaped_url.startswith(('http://', 'https://')):
315
+ raise ValueError(f"URL 缺少 HTTP(S) scheme: {escaped_url[:50]}...")
316
+
317
+ # 检查 URL 长度
318
+ if len(escaped_url) > 8192: # 大多数服务器支持的最大 URL 长度
319
+ raise ValueError(f"URL 过长 (超过 8192 字符): {len(escaped_url)} 字符")
320
+
321
+ self._url = escaped_url
322
+
323
+ @property
324
+ def url(self) -> str:
325
+ return self._url
326
+
327
+ @property
328
+ def meta(self) -> Dict[str, Any]:
329
+ return self._meta
330
+
331
+ def __str__(self) -> str:
332
+ return f'<Request url={self.url} method={self.method}>'
333
+
334
+ def __repr__(self) -> str:
335
+ return str(self)
336
+
337
+ def __lt__(self, other: _Request) -> bool:
338
+ """用于按优先级排序"""
312
339
  return self.priority < other.priority