crawlo 1.0.3__py3-none-any.whl → 1.0.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 +25 -9
- crawlo/__version__.py +1 -1
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +158 -158
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +57 -57
- crawlo/crawler.py +424 -242
- crawlo/downloader/__init__.py +78 -78
- crawlo/downloader/aiohttp_downloader.py +200 -259
- crawlo/downloader/cffi_downloader.py +277 -0
- crawlo/downloader/httpx_downloader.py +246 -187
- crawlo/event.py +11 -11
- crawlo/exceptions.py +73 -64
- crawlo/extension/__init__.py +31 -31
- crawlo/extension/log_interval.py +49 -49
- crawlo/extension/log_stats.py +44 -44
- crawlo/extension/logging_extension.py +35 -0
- crawlo/filters/__init__.py +37 -37
- crawlo/filters/aioredis_filter.py +150 -158
- crawlo/filters/memory_filter.py +202 -202
- crawlo/items/__init__.py +62 -62
- crawlo/items/items.py +115 -119
- crawlo/middleware/__init__.py +21 -21
- crawlo/middleware/default_header.py +32 -32
- crawlo/middleware/download_delay.py +28 -28
- crawlo/middleware/middleware_manager.py +135 -140
- crawlo/middleware/proxy.py +246 -0
- crawlo/middleware/request_ignore.py +30 -30
- crawlo/middleware/response_code.py +18 -18
- crawlo/middleware/response_filter.py +26 -26
- crawlo/middleware/retry.py +90 -90
- crawlo/network/__init__.py +7 -7
- crawlo/network/request.py +203 -204
- crawlo/network/response.py +166 -166
- crawlo/pipelines/__init__.py +13 -13
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/mongo_pipeline.py +116 -116
- crawlo/pipelines/mysql_batch_pipline.py +273 -134
- crawlo/pipelines/mysql_pipeline.py +195 -195
- crawlo/pipelines/pipeline_manager.py +56 -56
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +169 -93
- crawlo/settings/setting_manager.py +99 -99
- crawlo/spider/__init__.py +41 -36
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +106 -106
- crawlo/task_manager.py +27 -27
- crawlo/templates/item_template.tmpl +21 -21
- crawlo/templates/project_template/main.py +32 -32
- crawlo/templates/project_template/setting.py +189 -189
- crawlo/templates/spider_template.tmpl +30 -30
- crawlo/utils/__init__.py +7 -7
- crawlo/utils/concurrency_manager.py +124 -124
- crawlo/utils/date_tools.py +233 -177
- crawlo/utils/db_helper.py +344 -0
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/log.py +129 -39
- crawlo/utils/pqueue.py +173 -173
- crawlo/utils/project.py +59 -59
- crawlo/utils/request.py +267 -122
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +5 -303
- crawlo/utils/url.py +39 -39
- {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/METADATA +49 -48
- crawlo-1.0.5.dist-info/RECORD +84 -0
- {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/top_level.txt +1 -0
- examples/__init__.py +0 -0
- examples/gxb/__init__.py +0 -0
- examples/gxb/items.py +36 -0
- examples/gxb/run.py +15 -0
- examples/gxb/settings.py +71 -0
- examples/gxb/spider/__init__.py +0 -0
- examples/gxb/spider/miit_spider.py +180 -0
- examples/gxb/spider/telecom_device_licenses.py +129 -0
- tests/__init__.py +7 -7
- tests/test_proxy_health_check.py +33 -0
- tests/test_proxy_middleware_integration.py +137 -0
- tests/test_proxy_providers.py +57 -0
- tests/test_proxy_stats.py +20 -0
- tests/test_proxy_strategies.py +60 -0
- crawlo/downloader/playwright_downloader.py +0 -161
- crawlo/filters/redis_filter.py +0 -120
- crawlo-1.0.3.dist-info/RECORD +0 -80
- tests/baidu_spider/__init__.py +0 -7
- tests/baidu_spider/demo.py +0 -94
- tests/baidu_spider/items.py +0 -25
- tests/baidu_spider/middleware.py +0 -49
- tests/baidu_spider/pipeline.py +0 -55
- tests/baidu_spider/request_fingerprints.txt +0 -9
- tests/baidu_spider/run.py +0 -27
- tests/baidu_spider/settings.py +0 -78
- tests/baidu_spider/spiders/__init__.py +0 -7
- tests/baidu_spider/spiders/bai_du.py +0 -61
- tests/baidu_spider/spiders/sina.py +0 -79
- {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/WHEEL +0 -0
- {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/entry_points.txt +0 -0
|
@@ -1,125 +1,125 @@
|
|
|
1
|
-
import os
|
|
2
|
-
import platform
|
|
3
|
-
import logging
|
|
4
|
-
from typing import Optional
|
|
5
|
-
|
|
6
|
-
try:
|
|
7
|
-
import psutil # 用于获取系统资源信息的第三方库
|
|
8
|
-
except ImportError:
|
|
9
|
-
psutil = None # 如果psutil不可用则设为None
|
|
10
|
-
|
|
11
|
-
logger = logging.getLogger(__name__)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def calculate_optimal_concurrency(user_specified: Optional[int] = None, use_logical_cores: bool = True) -> int:
|
|
15
|
-
"""
|
|
16
|
-
基于系统资源计算最优并发数,或使用用户指定值
|
|
17
|
-
|
|
18
|
-
参数:
|
|
19
|
-
user_specified: 用户指定的并发数(优先使用)
|
|
20
|
-
use_logical_cores: 是否使用逻辑CPU核心数(超线程),默认为True
|
|
21
|
-
|
|
22
|
-
返回:
|
|
23
|
-
计算得出的最优并发数
|
|
24
|
-
|
|
25
|
-
说明:
|
|
26
|
-
1. 优先使用用户指定的并发数
|
|
27
|
-
2. 根据操作系统类型采用不同的计算策略:
|
|
28
|
-
- Windows: 保守计算,避免内存压力
|
|
29
|
-
- macOS: 平衡资源使用
|
|
30
|
-
- Linux: 充分利用服务器资源
|
|
31
|
-
- 其他系统: 使用合理默认值
|
|
32
|
-
3. 使用可用内存和CPU核心数进行计算
|
|
33
|
-
4. 提供psutil不可用时的备用方案
|
|
34
|
-
"""
|
|
35
|
-
# 优先使用用户指定的并发数
|
|
36
|
-
if user_specified is not None:
|
|
37
|
-
logger.info(f"使用用户指定的并发数: {user_specified}")
|
|
38
|
-
return user_specified
|
|
39
|
-
|
|
40
|
-
try:
|
|
41
|
-
current_os = platform.system() # 获取当前操作系统类型
|
|
42
|
-
logger.debug(f"检测到操作系统: {current_os}")
|
|
43
|
-
|
|
44
|
-
# 获取CPU核心数(根据参数决定是否使用逻辑核心)
|
|
45
|
-
cpu_count = psutil.cpu_count(logical=use_logical_cores) or 1 if psutil else os.cpu_count() or 1
|
|
46
|
-
|
|
47
|
-
# 根据操作系统类型选择不同的计算方法
|
|
48
|
-
if current_os == "Windows":
|
|
49
|
-
concurrency = _get_concurrency_for_windows(cpu_count, use_logical_cores)
|
|
50
|
-
elif current_os == "Darwin": # macOS系统
|
|
51
|
-
concurrency = _get_concurrency_for_macos(cpu_count, use_logical_cores)
|
|
52
|
-
elif current_os == "Linux":
|
|
53
|
-
concurrency = _get_concurrency_for_linux(cpu_count, use_logical_cores)
|
|
54
|
-
else: # 其他操作系统
|
|
55
|
-
concurrency = _get_concurrency_default(cpu_count)
|
|
56
|
-
|
|
57
|
-
logger.info(f"计算得到最大并发数: {concurrency}")
|
|
58
|
-
return concurrency
|
|
59
|
-
|
|
60
|
-
except Exception as e:
|
|
61
|
-
logger.warning(f"动态计算并发数失败: {str(e)},使用默认值50")
|
|
62
|
-
return 50 # 计算失败时的安全默认值
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def _get_concurrency_for_windows(cpu_count: int, use_logical_cores: bool) -> int:
|
|
66
|
-
"""Windows系统专用的并发数计算逻辑"""
|
|
67
|
-
if psutil:
|
|
68
|
-
# 计算可用内存(GB)
|
|
69
|
-
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
70
|
-
# 内存计算:每4GB可用内存分配10个并发
|
|
71
|
-
mem_based = int((available_memory / 4) * 10)
|
|
72
|
-
# CPU计算:使用逻辑核心时乘数较大
|
|
73
|
-
cpu_based = cpu_count * (5 if use_logical_cores else 3)
|
|
74
|
-
# 取5-100之间的值,选择内存和CPU限制中较小的
|
|
75
|
-
return max(5, min(100, mem_based, cpu_based))
|
|
76
|
-
else:
|
|
77
|
-
# 无psutil时的备用方案
|
|
78
|
-
return min(50, cpu_count * 5)
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def _get_concurrency_for_macos(cpu_count: int, use_logical_cores: bool) -> int:
|
|
82
|
-
"""macOS系统专用的并发数计算逻辑"""
|
|
83
|
-
if psutil:
|
|
84
|
-
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
85
|
-
# 内存计算:每3GB可用内存分配10个并发
|
|
86
|
-
mem_based = int((available_memory / 3) * 10)
|
|
87
|
-
# CPU计算:使用逻辑核心时乘数较大
|
|
88
|
-
cpu_based = cpu_count * (6 if use_logical_cores else 4)
|
|
89
|
-
# 取5-120之间的值
|
|
90
|
-
return max(5, min(120, mem_based, cpu_based))
|
|
91
|
-
else:
|
|
92
|
-
try:
|
|
93
|
-
# macOS备用方案:使用系统命令获取物理CPU核心数
|
|
94
|
-
import subprocess
|
|
95
|
-
output = subprocess.check_output(["sysctl", "hw.physicalcpu"])
|
|
96
|
-
cpu_count = int(output.split()[1])
|
|
97
|
-
return min(60, cpu_count * 5)
|
|
98
|
-
except:
|
|
99
|
-
return 40 # Mac电脑的合理默认值
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def _get_concurrency_for_linux(cpu_count: int, use_logical_cores: bool) -> int:
|
|
103
|
-
"""Linux系统专用的并发数计算逻辑(更激进)"""
|
|
104
|
-
if psutil:
|
|
105
|
-
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
106
|
-
# 内存计算:每1.5GB可用内存分配10个并发
|
|
107
|
-
mem_based = int((available_memory / 1.5) * 10)
|
|
108
|
-
# CPU计算:服务器环境使用更大的乘数
|
|
109
|
-
cpu_based = cpu_count * (8 if use_logical_cores else 5)
|
|
110
|
-
# 取5-200之间的值
|
|
111
|
-
return max(5, min(200, mem_based, cpu_based))
|
|
112
|
-
else:
|
|
113
|
-
try:
|
|
114
|
-
# Linux备用方案:解析/proc/cpuinfo文件
|
|
115
|
-
with open("/proc/cpuinfo") as f:
|
|
116
|
-
cpu_count = f.read().count("processor\t:")
|
|
117
|
-
if cpu_count > 0:
|
|
118
|
-
return min(200, cpu_count * 8)
|
|
119
|
-
except:
|
|
120
|
-
return 50 # Linux服务器的合理默认值
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
def _get_concurrency_default(cpu_count: int) -> int:
|
|
124
|
-
"""未知操作系统的默认计算逻辑"""
|
|
1
|
+
import os
|
|
2
|
+
import platform
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
import psutil # 用于获取系统资源信息的第三方库
|
|
8
|
+
except ImportError:
|
|
9
|
+
psutil = None # 如果psutil不可用则设为None
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def calculate_optimal_concurrency(user_specified: Optional[int] = None, use_logical_cores: bool = True) -> int:
|
|
15
|
+
"""
|
|
16
|
+
基于系统资源计算最优并发数,或使用用户指定值
|
|
17
|
+
|
|
18
|
+
参数:
|
|
19
|
+
user_specified: 用户指定的并发数(优先使用)
|
|
20
|
+
use_logical_cores: 是否使用逻辑CPU核心数(超线程),默认为True
|
|
21
|
+
|
|
22
|
+
返回:
|
|
23
|
+
计算得出的最优并发数
|
|
24
|
+
|
|
25
|
+
说明:
|
|
26
|
+
1. 优先使用用户指定的并发数
|
|
27
|
+
2. 根据操作系统类型采用不同的计算策略:
|
|
28
|
+
- Windows: 保守计算,避免内存压力
|
|
29
|
+
- macOS: 平衡资源使用
|
|
30
|
+
- Linux: 充分利用服务器资源
|
|
31
|
+
- 其他系统: 使用合理默认值
|
|
32
|
+
3. 使用可用内存和CPU核心数进行计算
|
|
33
|
+
4. 提供psutil不可用时的备用方案
|
|
34
|
+
"""
|
|
35
|
+
# 优先使用用户指定的并发数
|
|
36
|
+
if user_specified is not None:
|
|
37
|
+
logger.info(f"使用用户指定的并发数: {user_specified}")
|
|
38
|
+
return user_specified
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
current_os = platform.system() # 获取当前操作系统类型
|
|
42
|
+
logger.debug(f"检测到操作系统: {current_os}")
|
|
43
|
+
|
|
44
|
+
# 获取CPU核心数(根据参数决定是否使用逻辑核心)
|
|
45
|
+
cpu_count = psutil.cpu_count(logical=use_logical_cores) or 1 if psutil else os.cpu_count() or 1
|
|
46
|
+
|
|
47
|
+
# 根据操作系统类型选择不同的计算方法
|
|
48
|
+
if current_os == "Windows":
|
|
49
|
+
concurrency = _get_concurrency_for_windows(cpu_count, use_logical_cores)
|
|
50
|
+
elif current_os == "Darwin": # macOS系统
|
|
51
|
+
concurrency = _get_concurrency_for_macos(cpu_count, use_logical_cores)
|
|
52
|
+
elif current_os == "Linux":
|
|
53
|
+
concurrency = _get_concurrency_for_linux(cpu_count, use_logical_cores)
|
|
54
|
+
else: # 其他操作系统
|
|
55
|
+
concurrency = _get_concurrency_default(cpu_count)
|
|
56
|
+
|
|
57
|
+
logger.info(f"计算得到最大并发数: {concurrency}")
|
|
58
|
+
return concurrency
|
|
59
|
+
|
|
60
|
+
except Exception as e:
|
|
61
|
+
logger.warning(f"动态计算并发数失败: {str(e)},使用默认值50")
|
|
62
|
+
return 50 # 计算失败时的安全默认值
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _get_concurrency_for_windows(cpu_count: int, use_logical_cores: bool) -> int:
|
|
66
|
+
"""Windows系统专用的并发数计算逻辑"""
|
|
67
|
+
if psutil:
|
|
68
|
+
# 计算可用内存(GB)
|
|
69
|
+
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
70
|
+
# 内存计算:每4GB可用内存分配10个并发
|
|
71
|
+
mem_based = int((available_memory / 4) * 10)
|
|
72
|
+
# CPU计算:使用逻辑核心时乘数较大
|
|
73
|
+
cpu_based = cpu_count * (5 if use_logical_cores else 3)
|
|
74
|
+
# 取5-100之间的值,选择内存和CPU限制中较小的
|
|
75
|
+
return max(5, min(100, mem_based, cpu_based))
|
|
76
|
+
else:
|
|
77
|
+
# 无psutil时的备用方案
|
|
78
|
+
return min(50, cpu_count * 5)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _get_concurrency_for_macos(cpu_count: int, use_logical_cores: bool) -> int:
|
|
82
|
+
"""macOS系统专用的并发数计算逻辑"""
|
|
83
|
+
if psutil:
|
|
84
|
+
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
85
|
+
# 内存计算:每3GB可用内存分配10个并发
|
|
86
|
+
mem_based = int((available_memory / 3) * 10)
|
|
87
|
+
# CPU计算:使用逻辑核心时乘数较大
|
|
88
|
+
cpu_based = cpu_count * (6 if use_logical_cores else 4)
|
|
89
|
+
# 取5-120之间的值
|
|
90
|
+
return max(5, min(120, mem_based, cpu_based))
|
|
91
|
+
else:
|
|
92
|
+
try:
|
|
93
|
+
# macOS备用方案:使用系统命令获取物理CPU核心数
|
|
94
|
+
import subprocess
|
|
95
|
+
output = subprocess.check_output(["sysctl", "hw.physicalcpu"])
|
|
96
|
+
cpu_count = int(output.split()[1])
|
|
97
|
+
return min(60, cpu_count * 5)
|
|
98
|
+
except:
|
|
99
|
+
return 40 # Mac电脑的合理默认值
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _get_concurrency_for_linux(cpu_count: int, use_logical_cores: bool) -> int:
|
|
103
|
+
"""Linux系统专用的并发数计算逻辑(更激进)"""
|
|
104
|
+
if psutil:
|
|
105
|
+
available_memory = psutil.virtual_memory().available / (1024 ** 3)
|
|
106
|
+
# 内存计算:每1.5GB可用内存分配10个并发
|
|
107
|
+
mem_based = int((available_memory / 1.5) * 10)
|
|
108
|
+
# CPU计算:服务器环境使用更大的乘数
|
|
109
|
+
cpu_based = cpu_count * (8 if use_logical_cores else 5)
|
|
110
|
+
# 取5-200之间的值
|
|
111
|
+
return max(5, min(200, mem_based, cpu_based))
|
|
112
|
+
else:
|
|
113
|
+
try:
|
|
114
|
+
# Linux备用方案:解析/proc/cpuinfo文件
|
|
115
|
+
with open("/proc/cpuinfo") as f:
|
|
116
|
+
cpu_count = f.read().count("processor\t:")
|
|
117
|
+
if cpu_count > 0:
|
|
118
|
+
return min(200, cpu_count * 8)
|
|
119
|
+
except:
|
|
120
|
+
return 50 # Linux服务器的合理默认值
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _get_concurrency_default(cpu_count: int) -> int:
|
|
124
|
+
"""未知操作系统的默认计算逻辑"""
|
|
125
125
|
return min(50, cpu_count * 5) # 保守的默认计算方式
|
crawlo/utils/date_tools.py
CHANGED
|
@@ -1,177 +1,233 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
"""
|
|
4
|
-
# @Time :
|
|
5
|
-
# @Author :
|
|
6
|
-
# @Desc :
|
|
7
|
-
"""
|
|
8
|
-
import dateparser
|
|
9
|
-
from typing import Optional, Union
|
|
10
|
-
from datetime import datetime, timedelta
|
|
11
|
-
from dateutil.relativedelta import relativedelta
|
|
12
|
-
|
|
13
|
-
#
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"%Y
|
|
21
|
-
"%d
|
|
22
|
-
"%d
|
|
23
|
-
"%
|
|
24
|
-
"%
|
|
25
|
-
"%Y
|
|
26
|
-
"%Y
|
|
27
|
-
"%
|
|
28
|
-
"%
|
|
29
|
-
"%Y
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
""
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
:
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
def
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
# @Time : 2025-05-17 10:20
|
|
5
|
+
# @Author : crawl-coder
|
|
6
|
+
# @Desc : 智能时间工具库(专为爬虫场景设计)
|
|
7
|
+
"""
|
|
8
|
+
import dateparser
|
|
9
|
+
from typing import Optional, Union, Literal
|
|
10
|
+
from datetime import datetime, timedelta
|
|
11
|
+
from dateutil.relativedelta import relativedelta
|
|
12
|
+
|
|
13
|
+
# 支持的单位类型
|
|
14
|
+
TimeUnit = Literal["seconds", "minutes", "hours", "days"]
|
|
15
|
+
# 时间输入类型
|
|
16
|
+
TimeType = Union[str, datetime]
|
|
17
|
+
|
|
18
|
+
# 常见时间格式列表(作为 dateparser 的后备方案)
|
|
19
|
+
COMMON_FORMATS = [
|
|
20
|
+
"%Y-%m-%d %H:%M:%S",
|
|
21
|
+
"%Y/%m/%d %H:%M:%S",
|
|
22
|
+
"%d-%m-%Y %H:%M:%S",
|
|
23
|
+
"%d/%m/%Y %H:%M:%S",
|
|
24
|
+
"%Y-%m-%d",
|
|
25
|
+
"%Y/%m/%d",
|
|
26
|
+
"%d-%m-%Y",
|
|
27
|
+
"%d/%m/%Y",
|
|
28
|
+
"%b %d, %Y",
|
|
29
|
+
"%B %d, %Y",
|
|
30
|
+
"%Y年%m月%d日",
|
|
31
|
+
"%Y年%m月%d日 %H时%M分%S秒",
|
|
32
|
+
"%a %b %d %H:%M:%S %Y",
|
|
33
|
+
"%a, %d %b %Y %H:%M:%S",
|
|
34
|
+
"%Y-%m-%dT%H:%M:%S.%f",
|
|
35
|
+
"%Y-%m-%dT%H:%M:%S",
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class TimeUtils:
|
|
40
|
+
"""
|
|
41
|
+
时间处理工具类,提供日期解析、格式化、计算等一站式服务。
|
|
42
|
+
特别适用于爬虫中处理多语言、多格式、相对时间的场景。
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def _try_strptime(time_str: str) -> Optional[datetime]:
|
|
47
|
+
"""尝试使用预定义格式解析,作为 dateparser 的后备"""
|
|
48
|
+
for fmt in COMMON_FORMATS:
|
|
49
|
+
try:
|
|
50
|
+
return datetime.strptime(time_str.strip(), fmt)
|
|
51
|
+
except ValueError:
|
|
52
|
+
continue
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
@classmethod
|
|
56
|
+
def parse(cls, time_input: TimeType, *, default: Optional[datetime] = None) -> Optional[datetime]:
|
|
57
|
+
"""
|
|
58
|
+
智能解析时间输入(字符串或 datetime)。
|
|
59
|
+
|
|
60
|
+
:param time_input: 时间字符串(支持各种语言、格式、相对时间)或 datetime 对象
|
|
61
|
+
:param default: 解析失败时返回的默认值
|
|
62
|
+
:return: 解析成功返回 datetime,失败返回 default
|
|
63
|
+
"""
|
|
64
|
+
if isinstance(time_input, datetime):
|
|
65
|
+
return time_input
|
|
66
|
+
|
|
67
|
+
if not isinstance(time_input, str) or not time_input.strip():
|
|
68
|
+
return default
|
|
69
|
+
|
|
70
|
+
# 1. 优先使用 dateparser(支持多语言和相对时间)
|
|
71
|
+
try:
|
|
72
|
+
parsed = dateparser.parse(time_input.strip())
|
|
73
|
+
if parsed:
|
|
74
|
+
return parsed
|
|
75
|
+
except Exception:
|
|
76
|
+
pass # 忽略异常,尝试后备方案
|
|
77
|
+
|
|
78
|
+
# 2. 尝试使用常见格式解析
|
|
79
|
+
try:
|
|
80
|
+
parsed = cls._try_strptime(time_input)
|
|
81
|
+
if parsed:
|
|
82
|
+
return parsed
|
|
83
|
+
except Exception:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
return default
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def format(cls, dt: TimeType, fmt: str = "%Y-%m-%d %H:%M:%S") -> Optional[str]:
|
|
90
|
+
"""
|
|
91
|
+
格式化时间。
|
|
92
|
+
|
|
93
|
+
:param dt: datetime 对象或可解析的字符串
|
|
94
|
+
:param fmt: 输出格式
|
|
95
|
+
:return: 格式化后的字符串,失败返回 None
|
|
96
|
+
"""
|
|
97
|
+
if isinstance(dt, str):
|
|
98
|
+
dt = cls.parse(dt)
|
|
99
|
+
if dt is None:
|
|
100
|
+
return None
|
|
101
|
+
try:
|
|
102
|
+
return dt.strftime(fmt)
|
|
103
|
+
except Exception:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
@classmethod
|
|
107
|
+
def to_timestamp(cls, dt: TimeType) -> Optional[float]:
|
|
108
|
+
"""转换为时间戳(秒级)"""
|
|
109
|
+
if isinstance(dt, str):
|
|
110
|
+
dt = cls.parse(dt)
|
|
111
|
+
if dt is None:
|
|
112
|
+
return None
|
|
113
|
+
try:
|
|
114
|
+
return dt.timestamp()
|
|
115
|
+
except Exception:
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_timestamp(cls, ts: float) -> Optional[datetime]:
|
|
120
|
+
"""从时间戳创建 datetime"""
|
|
121
|
+
try:
|
|
122
|
+
return datetime.fromtimestamp(ts)
|
|
123
|
+
except Exception:
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def diff(cls, start: TimeType, end: TimeType, unit: TimeUnit = "seconds") -> Optional[int]:
|
|
128
|
+
"""
|
|
129
|
+
计算两个时间的差值(自动解析字符串)。
|
|
130
|
+
|
|
131
|
+
:param start: 起始时间
|
|
132
|
+
:param end: 结束时间
|
|
133
|
+
:param unit: 单位 ('seconds', 'minutes', 'hours', 'days')
|
|
134
|
+
:return: 差值(绝对值),失败返回 None
|
|
135
|
+
"""
|
|
136
|
+
start_dt = cls.parse(start)
|
|
137
|
+
end_dt = cls.parse(end)
|
|
138
|
+
if not start_dt or not end_dt:
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
delta = abs((end_dt - start_dt).total_seconds())
|
|
142
|
+
|
|
143
|
+
unit_map = {
|
|
144
|
+
"seconds": 1,
|
|
145
|
+
"minutes": 60,
|
|
146
|
+
"hours": 3600,
|
|
147
|
+
"days": 86400,
|
|
148
|
+
}
|
|
149
|
+
return int(delta // unit_map.get(unit, 1))
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def add_days(cls, dt: TimeType, days: int) -> Optional[datetime]:
|
|
153
|
+
"""日期加减(天)"""
|
|
154
|
+
dt = cls.parse(dt)
|
|
155
|
+
if dt is None:
|
|
156
|
+
return None
|
|
157
|
+
return dt + timedelta(days=days)
|
|
158
|
+
|
|
159
|
+
@classmethod
|
|
160
|
+
def add_months(cls, dt: TimeType, months: int) -> Optional[datetime]:
|
|
161
|
+
"""日期加减(月)"""
|
|
162
|
+
dt = cls.parse(dt)
|
|
163
|
+
if dt is None:
|
|
164
|
+
return None
|
|
165
|
+
return dt + relativedelta(months=months)
|
|
166
|
+
|
|
167
|
+
@classmethod
|
|
168
|
+
def days_between(cls, dt1: TimeType, dt2: TimeType) -> Optional[int]:
|
|
169
|
+
"""计算两个日期之间的天数差"""
|
|
170
|
+
return cls.diff(dt1, dt2, "days")
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def is_leap_year(cls, year: int) -> bool:
|
|
174
|
+
"""判断是否是闰年"""
|
|
175
|
+
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def now(cls, fmt: Optional[str] = None) -> Union[datetime, str]:
|
|
179
|
+
"""
|
|
180
|
+
获取当前时间。
|
|
181
|
+
|
|
182
|
+
:param fmt: 如果提供,则返回格式化字符串;否则返回 datetime 对象。
|
|
183
|
+
:return: datetime 或 str
|
|
184
|
+
"""
|
|
185
|
+
dt = datetime.now()
|
|
186
|
+
if fmt is not None:
|
|
187
|
+
return dt.strftime(fmt)
|
|
188
|
+
return dt
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def iso_format(cls, dt: TimeType) -> Optional[str]:
|
|
192
|
+
"""返回 ISO 8601 格式字符串"""
|
|
193
|
+
dt = cls.parse(dt)
|
|
194
|
+
if dt is None:
|
|
195
|
+
return None
|
|
196
|
+
return dt.isoformat()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# =======================对外接口=======================
|
|
200
|
+
|
|
201
|
+
def parse_time(time_input: TimeType, default: Optional[datetime] = None) -> Optional[datetime]:
|
|
202
|
+
"""解析时间字符串或对象"""
|
|
203
|
+
return TimeUtils.parse(time_input, default=default)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def format_time(dt: TimeType, fmt: str = "%Y-%m-%d %H:%M:%S") -> Optional[str]:
|
|
207
|
+
"""格式化时间"""
|
|
208
|
+
return TimeUtils.format(dt, fmt)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def time_diff(start: TimeType, end: TimeType, unit: TimeUnit = "seconds") -> Optional[int]:
|
|
212
|
+
"""计算时间差"""
|
|
213
|
+
return TimeUtils.diff(start, end, unit)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def to_timestamp(dt: TimeType) -> Optional[float]:
|
|
217
|
+
"""转时间戳"""
|
|
218
|
+
return TimeUtils.to_timestamp(dt)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def to_datetime(ts: float) -> Optional[datetime]:
|
|
222
|
+
"""从时间戳转 datetime"""
|
|
223
|
+
return TimeUtils.from_timestamp(ts)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def now(fmt: Optional[str] = None) -> Union[datetime, str]:
|
|
227
|
+
"""获取当前时间"""
|
|
228
|
+
return TimeUtils.now(fmt)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
if __name__ == '__main__':
|
|
232
|
+
get_current_time = now(fmt="%Y-%m-%d %H:%M:%S")
|
|
233
|
+
print(get_current_time)
|