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
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
# @Time : 2025-09-10 22:00
|
|
5
|
+
# @Author : crawl-coder
|
|
6
|
+
# @Desc : 反爬虫应对工具
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import random
|
|
11
|
+
import time
|
|
12
|
+
from typing import Dict, Any, Optional, List, Callable
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ProxyPoolManager:
|
|
16
|
+
"""代理池管理器类"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, proxies: Optional[List[Dict[str, str]]] = None):
|
|
19
|
+
"""
|
|
20
|
+
初始化代理池管理器
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
proxies (Optional[List[Dict[str, str]]]): 代理列表
|
|
24
|
+
"""
|
|
25
|
+
self.proxies = proxies or [
|
|
26
|
+
{"http": "http://proxy1.example.com:8080", "https": "https://proxy1.example.com:8080"},
|
|
27
|
+
{"http": "http://proxy2.example.com:8080", "https": "https://proxy2.example.com:8080"},
|
|
28
|
+
{"http": "http://proxy3.example.com:8080", "https": "https://proxy3.example.com:8080"}
|
|
29
|
+
]
|
|
30
|
+
self.proxy_status = {id(proxy): {"last_used": 0, "success_count": 0, "fail_count": 0}
|
|
31
|
+
for proxy in self.proxies}
|
|
32
|
+
|
|
33
|
+
def get_random_proxy(self) -> Dict[str, str]:
|
|
34
|
+
"""
|
|
35
|
+
获取随机代理
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
Dict[str, str]: 代理配置
|
|
39
|
+
"""
|
|
40
|
+
return random.choice(self.proxies)
|
|
41
|
+
|
|
42
|
+
def get_best_proxy(self) -> Dict[str, str]:
|
|
43
|
+
"""
|
|
44
|
+
根据成功率获取最佳代理
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
Dict[str, str]: 代理配置
|
|
48
|
+
"""
|
|
49
|
+
if not self.proxy_status:
|
|
50
|
+
return self.get_random_proxy()
|
|
51
|
+
|
|
52
|
+
# 计算每个代理的成功率
|
|
53
|
+
proxy_scores = []
|
|
54
|
+
for proxy in self.proxies:
|
|
55
|
+
proxy_id = id(proxy)
|
|
56
|
+
status = self.proxy_status.get(proxy_id, {"success_count": 0, "fail_count": 0})
|
|
57
|
+
total = status["success_count"] + status["fail_count"]
|
|
58
|
+
|
|
59
|
+
if total == 0:
|
|
60
|
+
score = 0.5 # 默认成功率
|
|
61
|
+
else:
|
|
62
|
+
score = status["success_count"] / total
|
|
63
|
+
|
|
64
|
+
proxy_scores.append((proxy, score))
|
|
65
|
+
|
|
66
|
+
# 按成功率排序,返回成功率最高的代理
|
|
67
|
+
proxy_scores.sort(key=lambda x: x[1], reverse=True)
|
|
68
|
+
return proxy_scores[0][0]
|
|
69
|
+
|
|
70
|
+
def report_proxy_result(self, proxy: Dict[str, str], success: bool) -> None:
|
|
71
|
+
"""
|
|
72
|
+
报告代理使用结果
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
proxy (Dict[str, str]): 代理配置
|
|
76
|
+
success (bool): 是否成功
|
|
77
|
+
"""
|
|
78
|
+
proxy_id = id(proxy)
|
|
79
|
+
if proxy_id not in self.proxy_status:
|
|
80
|
+
self.proxy_status[proxy_id] = {"last_used": 0, "success_count": 0, "fail_count": 0}
|
|
81
|
+
|
|
82
|
+
status = self.proxy_status[proxy_id]
|
|
83
|
+
status["last_used"] = time.time()
|
|
84
|
+
|
|
85
|
+
if success:
|
|
86
|
+
status["success_count"] += 1
|
|
87
|
+
else:
|
|
88
|
+
status["fail_count"] += 1
|
|
89
|
+
|
|
90
|
+
def remove_invalid_proxy(self, proxy: Dict[str, str]) -> None:
|
|
91
|
+
"""
|
|
92
|
+
移除无效代理
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
proxy (Dict[str, str]): 代理配置
|
|
96
|
+
"""
|
|
97
|
+
if proxy in self.proxies:
|
|
98
|
+
self.proxies.remove(proxy)
|
|
99
|
+
proxy_id = id(proxy)
|
|
100
|
+
if proxy_id in self.proxy_status:
|
|
101
|
+
del self.proxy_status[proxy_id]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class CaptchaHandler:
|
|
105
|
+
"""验证码处理器类"""
|
|
106
|
+
|
|
107
|
+
def __init__(self, captcha_service: Optional[Callable] = None):
|
|
108
|
+
"""
|
|
109
|
+
初始化验证码处理器
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
captcha_service (Optional[Callable]): 验证码识别服务
|
|
113
|
+
"""
|
|
114
|
+
self.captcha_service = captcha_service
|
|
115
|
+
|
|
116
|
+
async def recognize_captcha(self, image_data: bytes,
|
|
117
|
+
captcha_type: str = "image") -> Optional[str]:
|
|
118
|
+
"""
|
|
119
|
+
识别验证码
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
image_data (bytes): 验证码图片数据
|
|
123
|
+
captcha_type (str): 验证码类型
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
Optional[str]: 识别结果
|
|
127
|
+
"""
|
|
128
|
+
if self.captcha_service:
|
|
129
|
+
try:
|
|
130
|
+
return await self.captcha_service(image_data, captcha_type)
|
|
131
|
+
except Exception:
|
|
132
|
+
return None
|
|
133
|
+
else:
|
|
134
|
+
# 如果没有配置验证码服务,返回None
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
async def handle_manual_captcha(self, prompt: str = "请输入验证码: ") -> str:
|
|
138
|
+
"""
|
|
139
|
+
处理手动验证码输入
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
prompt (str): 提示信息
|
|
143
|
+
|
|
144
|
+
Returns:
|
|
145
|
+
str: 用户输入的验证码
|
|
146
|
+
"""
|
|
147
|
+
# 在实际应用中,这里可能需要与用户界面交互
|
|
148
|
+
# 为了演示目的,我们模拟用户输入
|
|
149
|
+
print(prompt)
|
|
150
|
+
return input() if not asyncio.get_event_loop().is_running() else ""
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class AntiCrawler:
|
|
154
|
+
"""反爬虫应对工具类"""
|
|
155
|
+
|
|
156
|
+
def __init__(self, proxies: Optional[List[Dict[str, str]]] = None,
|
|
157
|
+
captcha_service: Optional[Callable] = None):
|
|
158
|
+
"""
|
|
159
|
+
初始化反爬虫应对工具
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
proxies (Optional[List[Dict[str, str]]]): 代理列表
|
|
163
|
+
captcha_service (Optional[Callable]): 验证码识别服务
|
|
164
|
+
"""
|
|
165
|
+
self.proxy_manager = ProxyPoolManager(proxies)
|
|
166
|
+
self.captcha_handler = CaptchaHandler(captcha_service)
|
|
167
|
+
|
|
168
|
+
def get_random_user_agent(self) -> str:
|
|
169
|
+
"""
|
|
170
|
+
获取随机User-Agent
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
str: 随机User-Agent
|
|
174
|
+
"""
|
|
175
|
+
user_agents = [
|
|
176
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
|
177
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
|
178
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0",
|
|
179
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15",
|
|
180
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.59",
|
|
181
|
+
"Mozilla/5.0 (iPhone; CPU iPhone OS 14_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1",
|
|
182
|
+
"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36"
|
|
183
|
+
]
|
|
184
|
+
return random.choice(user_agents)
|
|
185
|
+
|
|
186
|
+
def rotate_proxy(self) -> Dict[str, str]:
|
|
187
|
+
"""
|
|
188
|
+
轮换代理
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
Dict[str, str]: 代理配置
|
|
192
|
+
"""
|
|
193
|
+
return self.proxy_manager.get_best_proxy()
|
|
194
|
+
|
|
195
|
+
def handle_captcha(self, response_text: str) -> bool:
|
|
196
|
+
"""
|
|
197
|
+
检测是否遇到验证码
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
response_text (str): 响应文本
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
bool: 是否遇到验证码
|
|
204
|
+
"""
|
|
205
|
+
captcha_keywords = ["captcha", "verify", "验证", "验证码", "human verification"]
|
|
206
|
+
return any(keyword in response_text.lower() for keyword in captcha_keywords)
|
|
207
|
+
|
|
208
|
+
def detect_rate_limiting(self, status_code: int, response_headers: Dict[str, Any]) -> bool:
|
|
209
|
+
"""
|
|
210
|
+
检测是否遇到频率限制
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
status_code (int): HTTP状态码
|
|
214
|
+
response_headers (Dict[str, Any]): 响应头
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
bool: 是否遇到频率限制
|
|
218
|
+
"""
|
|
219
|
+
# 检查状态码
|
|
220
|
+
if status_code in [429, 503]:
|
|
221
|
+
return True
|
|
222
|
+
|
|
223
|
+
# 检查响应头
|
|
224
|
+
rate_limit_headers = ["x-ratelimit-remaining", "retry-after", "x-ratelimit-reset"]
|
|
225
|
+
return any(header.lower() in [k.lower() for k in response_headers.keys()]
|
|
226
|
+
for header in rate_limit_headers)
|
|
227
|
+
|
|
228
|
+
def random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> None:
|
|
229
|
+
"""
|
|
230
|
+
随机延迟,避免请求过于频繁
|
|
231
|
+
|
|
232
|
+
Args:
|
|
233
|
+
min_delay (float): 最小延迟时间(秒)
|
|
234
|
+
max_delay (float): 最大延迟时间(秒)
|
|
235
|
+
"""
|
|
236
|
+
delay = random.uniform(min_delay, max_delay)
|
|
237
|
+
time.sleep(delay)
|
|
238
|
+
|
|
239
|
+
async def async_random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> None:
|
|
240
|
+
"""
|
|
241
|
+
异步随机延迟,避免请求过于频繁
|
|
242
|
+
|
|
243
|
+
Args:
|
|
244
|
+
min_delay (float): 最小延迟时间(秒)
|
|
245
|
+
max_delay (float): 最大延迟时间(秒)
|
|
246
|
+
"""
|
|
247
|
+
delay = random.uniform(min_delay, max_delay)
|
|
248
|
+
await asyncio.sleep(delay)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# 便捷函数
|
|
252
|
+
def get_random_user_agent() -> str:
|
|
253
|
+
"""获取随机User-Agent"""
|
|
254
|
+
return AntiCrawler().get_random_user_agent()
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def rotate_proxy(proxies: Optional[List[Dict[str, str]]] = None) -> Dict[str, str]:
|
|
258
|
+
"""轮换代理"""
|
|
259
|
+
return AntiCrawler(proxies).rotate_proxy()
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def handle_captcha(response_text: str) -> bool:
|
|
263
|
+
"""检测是否遇到验证码"""
|
|
264
|
+
return AntiCrawler().handle_captcha(response_text)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def detect_rate_limiting(status_code: int, response_headers: Dict[str, Any]) -> bool:
|
|
268
|
+
"""检测是否遇到频率限制"""
|
|
269
|
+
return AntiCrawler().detect_rate_limiting(status_code, response_headers)
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
带认证代理工具
|
|
5
|
+
=============
|
|
6
|
+
支持带用户名密码认证的代理和非认证代理的统一处理工具
|
|
7
|
+
|
|
8
|
+
功能特性:
|
|
9
|
+
- 支持HTTP/HTTPS/SOCKS代理
|
|
10
|
+
- 支持带认证和不带认证的代理
|
|
11
|
+
- 统一的代理格式处理
|
|
12
|
+
- 代理有效性检测
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from typing import Dict, Any, Optional, Union
|
|
16
|
+
from urllib.parse import urlparse, urlunparse
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AuthenticatedProxy:
|
|
20
|
+
"""带认证代理处理类"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, proxy_url: str):
|
|
23
|
+
"""
|
|
24
|
+
初始化代理对象
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
proxy_url (str): 代理URL,支持带认证信息的格式
|
|
28
|
+
- 带认证: http://username:password@proxy.example.com:8080
|
|
29
|
+
- 无认证: http://proxy.example.com:8080
|
|
30
|
+
"""
|
|
31
|
+
self.proxy_url = proxy_url
|
|
32
|
+
self.parsed = urlparse(proxy_url)
|
|
33
|
+
|
|
34
|
+
# 提取认证信息
|
|
35
|
+
self.username = self.parsed.username
|
|
36
|
+
self.password = self.parsed.password
|
|
37
|
+
|
|
38
|
+
# 构造不带认证信息的URL
|
|
39
|
+
self.clean_url = urlunparse((
|
|
40
|
+
self.parsed.scheme,
|
|
41
|
+
f"{self.parsed.hostname}:{self.parsed.port}" if self.parsed.port else self.parsed.hostname,
|
|
42
|
+
self.parsed.path,
|
|
43
|
+
self.parsed.params,
|
|
44
|
+
self.parsed.query,
|
|
45
|
+
self.parsed.fragment
|
|
46
|
+
))
|
|
47
|
+
|
|
48
|
+
# 构造下载器兼容的代理字典
|
|
49
|
+
self.proxy_dict = {
|
|
50
|
+
"http": self.clean_url,
|
|
51
|
+
"https": self.clean_url
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
# 如果有认证信息,构造认证字符串
|
|
55
|
+
if self.username and self.password:
|
|
56
|
+
self.auth_string = f"{self.username}:{self.password}"
|
|
57
|
+
else:
|
|
58
|
+
self.auth_string = None
|
|
59
|
+
|
|
60
|
+
def get_proxy_for_downloader(self) -> Union[str, Dict[str, str]]:
|
|
61
|
+
"""
|
|
62
|
+
获取适用于下载器的代理配置
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
Union[str, Dict[str, str]]: 代理配置
|
|
66
|
+
- 对于AioHttp/CurlCffi: 返回字典格式 {"http": "...", "https": "..."}
|
|
67
|
+
- 对于HttpX: 可以直接使用字符串或字典格式
|
|
68
|
+
"""
|
|
69
|
+
return self.proxy_dict
|
|
70
|
+
|
|
71
|
+
def get_auth_credentials(self) -> Optional[Dict[str, str]]:
|
|
72
|
+
"""
|
|
73
|
+
获取认证凭据
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
Optional[Dict[str, str]]: 认证凭据 {"username": "...", "password": "..."}
|
|
77
|
+
"""
|
|
78
|
+
if self.username and self.password:
|
|
79
|
+
return {
|
|
80
|
+
"username": self.username,
|
|
81
|
+
"password": self.password
|
|
82
|
+
}
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
def get_auth_header(self) -> Optional[str]:
|
|
86
|
+
"""
|
|
87
|
+
获取Basic Auth认证头
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
Optional[str]: Basic Auth头信息
|
|
91
|
+
"""
|
|
92
|
+
if self.username and self.password:
|
|
93
|
+
import base64
|
|
94
|
+
credentials = f"{self.username}:{self.password}"
|
|
95
|
+
encoded = base64.b64encode(credentials.encode()).decode()
|
|
96
|
+
return f"Basic {encoded}"
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
def is_valid(self) -> bool:
|
|
100
|
+
"""
|
|
101
|
+
检查代理URL是否有效
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
bool: 代理URL是否有效
|
|
105
|
+
"""
|
|
106
|
+
# 检查协议
|
|
107
|
+
if self.parsed.scheme not in ["http", "https", "socks4", "socks5"]:
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
# 检查主机名
|
|
111
|
+
if not self.parsed.hostname:
|
|
112
|
+
return False
|
|
113
|
+
|
|
114
|
+
# 检查端口(如果指定)
|
|
115
|
+
if self.parsed.port and (self.parsed.port < 1 or self.parsed.port > 65535):
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
return True
|
|
119
|
+
|
|
120
|
+
def __str__(self) -> str:
|
|
121
|
+
return self.proxy_url
|
|
122
|
+
|
|
123
|
+
def __repr__(self) -> str:
|
|
124
|
+
return f"AuthenticatedProxy(url='{self.proxy_url}', username={self.username is not None})"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def create_proxy_config(proxy_url: str) -> Dict[str, Any]:
|
|
128
|
+
"""
|
|
129
|
+
创建代理配置,兼容各种下载器
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
proxy_url (str): 代理URL
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
Dict[str, Any]: 代理配置字典
|
|
136
|
+
"""
|
|
137
|
+
proxy = AuthenticatedProxy(proxy_url)
|
|
138
|
+
|
|
139
|
+
if not proxy.is_valid():
|
|
140
|
+
raise ValueError(f"Invalid proxy URL: {proxy_url}")
|
|
141
|
+
|
|
142
|
+
config = {
|
|
143
|
+
"url": proxy.clean_url,
|
|
144
|
+
"proxy_dict": proxy.proxy_dict,
|
|
145
|
+
"has_auth": proxy.auth_string is not None
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if proxy.auth_string:
|
|
149
|
+
config["auth"] = proxy.get_auth_credentials()
|
|
150
|
+
config["auth_header"] = proxy.get_auth_header()
|
|
151
|
+
|
|
152
|
+
return config
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def format_proxy_for_request(proxy_config: Dict[str, Any], downloader_type: str = "aiohttp") -> Dict[str, Any]:
|
|
156
|
+
"""
|
|
157
|
+
格式化代理配置以适配特定下载器
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
proxy_config (Dict[str, Any]): 代理配置
|
|
161
|
+
downloader_type (str): 下载器类型 (aiohttp, httpx, curl_cffi)
|
|
162
|
+
|
|
163
|
+
Returns:
|
|
164
|
+
Dict[str, Any]: 适配下载器的代理配置
|
|
165
|
+
"""
|
|
166
|
+
formatted = {}
|
|
167
|
+
|
|
168
|
+
if downloader_type.lower() == "aiohttp":
|
|
169
|
+
# AioHttp使用proxy和proxy_auth参数
|
|
170
|
+
formatted["proxy"] = proxy_config["url"]
|
|
171
|
+
if proxy_config.get("has_auth") and proxy_config.get("auth"):
|
|
172
|
+
from aiohttp import BasicAuth
|
|
173
|
+
auth = proxy_config["auth"]
|
|
174
|
+
formatted["proxy_auth"] = BasicAuth(auth["username"], auth["password"])
|
|
175
|
+
|
|
176
|
+
elif downloader_type.lower() == "httpx":
|
|
177
|
+
# HttpX可以直接使用代理URL字符串或字典
|
|
178
|
+
formatted["proxy"] = proxy_config["url"]
|
|
179
|
+
|
|
180
|
+
elif downloader_type.lower() == "curl_cffi":
|
|
181
|
+
# CurlCffi使用proxies字典
|
|
182
|
+
formatted["proxies"] = proxy_config["proxy_dict"]
|
|
183
|
+
# 认证信息包含在URL中或通过headers传递
|
|
184
|
+
if proxy_config.get("auth_header"):
|
|
185
|
+
formatted["headers"] = {"Proxy-Authorization": proxy_config["auth_header"]}
|
|
186
|
+
|
|
187
|
+
return formatted
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# 便捷函数
|
|
191
|
+
def parse_proxy_url(proxy_url: str) -> Dict[str, Any]:
|
|
192
|
+
"""
|
|
193
|
+
解析代理URL并返回详细信息
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
proxy_url (str): 代理URL
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
Dict[str, Any]: 代理详细信息
|
|
200
|
+
"""
|
|
201
|
+
return create_proxy_config(proxy_url)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def validate_proxy_url(proxy_url: str) -> bool:
|
|
205
|
+
"""
|
|
206
|
+
验证代理URL是否有效
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
proxy_url (str): 代理URL
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
bool: 是否有效
|
|
213
|
+
"""
|
|
214
|
+
try:
|
|
215
|
+
proxy = AuthenticatedProxy(proxy_url)
|
|
216
|
+
return proxy.is_valid()
|
|
217
|
+
except:
|
|
218
|
+
return False
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def get_proxy_info(proxy_url: str) -> Dict[str, Any]:
|
|
222
|
+
"""
|
|
223
|
+
获取代理详细信息
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
proxy_url (str): 代理URL
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
Dict[str, Any]: 代理详细信息
|
|
230
|
+
"""
|
|
231
|
+
proxy = AuthenticatedProxy(proxy_url)
|
|
232
|
+
return {
|
|
233
|
+
"original_url": proxy.proxy_url,
|
|
234
|
+
"clean_url": proxy.clean_url,
|
|
235
|
+
"scheme": proxy.parsed.scheme,
|
|
236
|
+
"hostname": proxy.parsed.hostname,
|
|
237
|
+
"port": proxy.parsed.port,
|
|
238
|
+
"has_auth": proxy.auth_string is not None,
|
|
239
|
+
"username": proxy.username,
|
|
240
|
+
"is_valid": proxy.is_valid()
|
|
241
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
# @Time : 2025-09-10 22:00
|
|
5
|
+
# @Author : crawl-coder
|
|
6
|
+
# @Desc : 数据验证工具
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from typing import Any, Union, Dict, List
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from urllib.parse import urlparse
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class DataValidator:
|
|
16
|
+
"""数据验证工具类"""
|
|
17
|
+
|
|
18
|
+
@staticmethod
|
|
19
|
+
def validate_email(email: str) -> bool:
|
|
20
|
+
"""
|
|
21
|
+
验证邮箱地址格式
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
email (str): 邮箱地址
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
bool: 验证结果
|
|
28
|
+
"""
|
|
29
|
+
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
|
|
30
|
+
return bool(re.match(pattern, email))
|
|
31
|
+
|
|
32
|
+
@staticmethod
|
|
33
|
+
def validate_phone(phone: str, country_code: str = "CN") -> bool:
|
|
34
|
+
"""
|
|
35
|
+
验证电话号码格式
|
|
36
|
+
|
|
37
|
+
Args:
|
|
38
|
+
phone (str): 电话号码
|
|
39
|
+
country_code (str): 国家代码,默认为"CN"
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
bool: 验证结果
|
|
43
|
+
"""
|
|
44
|
+
if country_code == "CN":
|
|
45
|
+
# 中国手机号码格式
|
|
46
|
+
pattern = r'^1[3-9]\d{9}$'
|
|
47
|
+
return bool(re.match(pattern, phone))
|
|
48
|
+
else:
|
|
49
|
+
# 通用格式,只检查是否全为数字且长度在7-15之间
|
|
50
|
+
pattern = r'^\d{7,15}$'
|
|
51
|
+
return bool(re.match(pattern, phone))
|
|
52
|
+
|
|
53
|
+
@staticmethod
|
|
54
|
+
def validate_url(url: str) -> bool:
|
|
55
|
+
"""
|
|
56
|
+
验证URL格式
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
url (str): URL地址
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
bool: 验证结果
|
|
63
|
+
"""
|
|
64
|
+
try:
|
|
65
|
+
result = urlparse(url)
|
|
66
|
+
return all([result.scheme, result.netloc])
|
|
67
|
+
except Exception:
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
@staticmethod
|
|
71
|
+
def validate_chinese_id_card(id_card: str) -> bool:
|
|
72
|
+
"""
|
|
73
|
+
验证中国身份证号码格式
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
id_card (str): 身份证号码
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
bool: 验证结果
|
|
80
|
+
"""
|
|
81
|
+
# 18位身份证号码格式
|
|
82
|
+
pattern = r'^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$'
|
|
83
|
+
return bool(re.match(pattern, id_card))
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def validate_date(date_str: str, date_format: str = "%Y-%m-%d") -> bool:
|
|
87
|
+
"""
|
|
88
|
+
验证日期格式
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
date_str (str): 日期字符串
|
|
92
|
+
date_format (str): 日期格式,默认为"%Y-%m-%d"
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
bool: 验证结果
|
|
96
|
+
"""
|
|
97
|
+
try:
|
|
98
|
+
datetime.strptime(date_str, date_format)
|
|
99
|
+
return True
|
|
100
|
+
except ValueError:
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def validate_number_range(value: Union[int, float], min_val: Union[int, float],
|
|
105
|
+
max_val: Union[int, float]) -> bool:
|
|
106
|
+
"""
|
|
107
|
+
验证数值是否在指定范围内
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
value (Union[int, float]): 要验证的数值
|
|
111
|
+
min_val (Union[int, float]): 最小值
|
|
112
|
+
max_val (Union[int, float]): 最大值
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
bool: 验证结果
|
|
116
|
+
"""
|
|
117
|
+
return min_val <= value <= max_val
|
|
118
|
+
|
|
119
|
+
@staticmethod
|
|
120
|
+
def check_data_integrity(data: Dict[str, Any], required_fields: List[str]) -> Dict[str, Any]:
|
|
121
|
+
"""
|
|
122
|
+
检查数据完整性,确保关键字段不为空
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
data (Dict[str, Any]): 要检查的数据
|
|
126
|
+
required_fields (List[str]): 必需字段列表
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
Dict[str, Any]: 检查结果,包含缺失字段和空值字段
|
|
130
|
+
"""
|
|
131
|
+
missing_fields = []
|
|
132
|
+
empty_fields = []
|
|
133
|
+
|
|
134
|
+
for field in required_fields:
|
|
135
|
+
if field not in data:
|
|
136
|
+
missing_fields.append(field)
|
|
137
|
+
elif data[field] is None or data[field] == "":
|
|
138
|
+
empty_fields.append(field)
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"is_valid": len(missing_fields) == 0 and len(empty_fields) == 0,
|
|
142
|
+
"missing_fields": missing_fields,
|
|
143
|
+
"empty_fields": empty_fields
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# 便捷函数
|
|
148
|
+
def validate_email(email: str) -> bool:
|
|
149
|
+
"""验证邮箱地址格式"""
|
|
150
|
+
return DataValidator.validate_email(email)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def validate_phone(phone: str, country_code: str = "CN") -> bool:
|
|
154
|
+
"""验证电话号码格式"""
|
|
155
|
+
return DataValidator.validate_phone(phone, country_code)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def validate_url(url: str) -> bool:
|
|
159
|
+
"""验证URL格式"""
|
|
160
|
+
return DataValidator.validate_url(url)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def validate_chinese_id_card(id_card: str) -> bool:
|
|
164
|
+
"""验证中国身份证号码格式"""
|
|
165
|
+
return DataValidator.validate_chinese_id_card(id_card)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def validate_date(date_str: str, date_format: str = "%Y-%m-%d") -> bool:
|
|
169
|
+
"""验证日期格式"""
|
|
170
|
+
return DataValidator.validate_date(date_str, date_format)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def validate_number_range(value: Union[int, float], min_val: Union[int, float],
|
|
174
|
+
max_val: Union[int, float]) -> bool:
|
|
175
|
+
"""验证数值是否在指定范围内"""
|
|
176
|
+
return DataValidator.validate_number_range(value, min_val, max_val)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def check_data_integrity(data: Dict[str, Any], required_fields: List[str]) -> Dict[str, Any]:
|
|
180
|
+
"""检查数据完整性"""
|
|
181
|
+
return DataValidator.check_data_integrity(data, required_fields)
|