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.

Files changed (96) hide show
  1. crawlo/__init__.py +25 -9
  2. crawlo/__version__.py +1 -1
  3. crawlo/core/__init__.py +2 -2
  4. crawlo/core/engine.py +158 -158
  5. crawlo/core/processor.py +40 -40
  6. crawlo/core/scheduler.py +57 -57
  7. crawlo/crawler.py +424 -242
  8. crawlo/downloader/__init__.py +78 -78
  9. crawlo/downloader/aiohttp_downloader.py +200 -259
  10. crawlo/downloader/cffi_downloader.py +277 -0
  11. crawlo/downloader/httpx_downloader.py +246 -187
  12. crawlo/event.py +11 -11
  13. crawlo/exceptions.py +73 -64
  14. crawlo/extension/__init__.py +31 -31
  15. crawlo/extension/log_interval.py +49 -49
  16. crawlo/extension/log_stats.py +44 -44
  17. crawlo/extension/logging_extension.py +35 -0
  18. crawlo/filters/__init__.py +37 -37
  19. crawlo/filters/aioredis_filter.py +150 -158
  20. crawlo/filters/memory_filter.py +202 -202
  21. crawlo/items/__init__.py +62 -62
  22. crawlo/items/items.py +115 -119
  23. crawlo/middleware/__init__.py +21 -21
  24. crawlo/middleware/default_header.py +32 -32
  25. crawlo/middleware/download_delay.py +28 -28
  26. crawlo/middleware/middleware_manager.py +135 -140
  27. crawlo/middleware/proxy.py +246 -0
  28. crawlo/middleware/request_ignore.py +30 -30
  29. crawlo/middleware/response_code.py +18 -18
  30. crawlo/middleware/response_filter.py +26 -26
  31. crawlo/middleware/retry.py +90 -90
  32. crawlo/network/__init__.py +7 -7
  33. crawlo/network/request.py +203 -204
  34. crawlo/network/response.py +166 -166
  35. crawlo/pipelines/__init__.py +13 -13
  36. crawlo/pipelines/console_pipeline.py +39 -39
  37. crawlo/pipelines/mongo_pipeline.py +116 -116
  38. crawlo/pipelines/mysql_batch_pipline.py +273 -134
  39. crawlo/pipelines/mysql_pipeline.py +195 -195
  40. crawlo/pipelines/pipeline_manager.py +56 -56
  41. crawlo/settings/__init__.py +7 -7
  42. crawlo/settings/default_settings.py +169 -93
  43. crawlo/settings/setting_manager.py +99 -99
  44. crawlo/spider/__init__.py +41 -36
  45. crawlo/stats_collector.py +59 -59
  46. crawlo/subscriber.py +106 -106
  47. crawlo/task_manager.py +27 -27
  48. crawlo/templates/item_template.tmpl +21 -21
  49. crawlo/templates/project_template/main.py +32 -32
  50. crawlo/templates/project_template/setting.py +189 -189
  51. crawlo/templates/spider_template.tmpl +30 -30
  52. crawlo/utils/__init__.py +7 -7
  53. crawlo/utils/concurrency_manager.py +124 -124
  54. crawlo/utils/date_tools.py +233 -177
  55. crawlo/utils/db_helper.py +344 -0
  56. crawlo/utils/func_tools.py +82 -82
  57. crawlo/utils/log.py +129 -39
  58. crawlo/utils/pqueue.py +173 -173
  59. crawlo/utils/project.py +59 -59
  60. crawlo/utils/request.py +267 -122
  61. crawlo/utils/system.py +11 -11
  62. crawlo/utils/tools.py +5 -303
  63. crawlo/utils/url.py +39 -39
  64. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/METADATA +49 -48
  65. crawlo-1.0.5.dist-info/RECORD +84 -0
  66. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/top_level.txt +1 -0
  67. examples/__init__.py +0 -0
  68. examples/gxb/__init__.py +0 -0
  69. examples/gxb/items.py +36 -0
  70. examples/gxb/run.py +15 -0
  71. examples/gxb/settings.py +71 -0
  72. examples/gxb/spider/__init__.py +0 -0
  73. examples/gxb/spider/miit_spider.py +180 -0
  74. examples/gxb/spider/telecom_device_licenses.py +129 -0
  75. tests/__init__.py +7 -7
  76. tests/test_proxy_health_check.py +33 -0
  77. tests/test_proxy_middleware_integration.py +137 -0
  78. tests/test_proxy_providers.py +57 -0
  79. tests/test_proxy_stats.py +20 -0
  80. tests/test_proxy_strategies.py +60 -0
  81. crawlo/downloader/playwright_downloader.py +0 -161
  82. crawlo/filters/redis_filter.py +0 -120
  83. crawlo-1.0.3.dist-info/RECORD +0 -80
  84. tests/baidu_spider/__init__.py +0 -7
  85. tests/baidu_spider/demo.py +0 -94
  86. tests/baidu_spider/items.py +0 -25
  87. tests/baidu_spider/middleware.py +0 -49
  88. tests/baidu_spider/pipeline.py +0 -55
  89. tests/baidu_spider/request_fingerprints.txt +0 -9
  90. tests/baidu_spider/run.py +0 -27
  91. tests/baidu_spider/settings.py +0 -78
  92. tests/baidu_spider/spiders/__init__.py +0 -7
  93. tests/baidu_spider/spiders/bai_du.py +0 -61
  94. tests/baidu_spider/spiders/sina.py +0 -79
  95. {crawlo-1.0.3.dist-info → crawlo-1.0.5.dist-info}/WHEEL +0 -0
  96. {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) # 保守的默认计算方式
@@ -1,177 +1,233 @@
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
10
- from datetime import datetime, timedelta
11
- from dateutil.relativedelta import relativedelta
12
-
13
- # 常见时间格式列表
14
- COMMON_FORMATS = [
15
- "%Y-%m-%d %H:%M:%S",
16
- "%Y/%m/%d %H:%M:%S",
17
- "%d-%m-%Y %H:%M:%S",
18
- "%d/%m/%Y %H:%M:%S",
19
- "%Y-%m-%d",
20
- "%Y/%m/%d",
21
- "%d-%m-%Y",
22
- "%d/%m/%Y",
23
- "%b %d, %Y", # Jan 01, 2023
24
- "%B %d, %Y", # January 01, 2023
25
- "%Y年%m月%d", # 2023年01月01日
26
- "%Y年%m月%d日 %H时%M分%S秒", # 2023年01月01日 12时30分45秒
27
- "%a %b %d %H:%M:%S %Y", # Wed Jan 01 12:00:00 2020
28
- "%a, %d %b %Y %H:%M:%S", # Wed, 01 Jan 2020 12:00:00
29
- "%Y-%m-%dT%H:%M:%S.%f", # ✅ 新增:ISO 8601 格式(带毫秒)
30
- ]
31
-
32
-
33
- def normalize_time(time_str: str) -> Optional[datetime]:
34
- """
35
- 尝试使用常见格式解析时间字符串。
36
-
37
- :param time_str: 时间字符串(如 "2023-01-01 12:00:00")
38
- :return: 解析成功返回 datetime 对象,失败返回 None 或抛出异常(可选)
39
- """
40
- for fmt in COMMON_FORMATS:
41
- try:
42
- return datetime.strptime(time_str, fmt)
43
- except ValueError:
44
- continue
45
- raise ValueError(f"无法解析时间字符串:{time_str}")
46
-
47
-
48
- def get_current_time(fmt: str = '%Y-%m-%d %H:%M:%S'):
49
- """
50
- 获取当前时间,根据是否传入格式化参数决定返回类型
51
- :param fmt: 格式化字符串,如 "%Y-%m-%d %H:%M:%S"
52
- :return: datetime 或 str
53
- """
54
- dt = datetime.now()
55
- if fmt is not None:
56
- return dt.strftime(fmt)
57
- return dt
58
-
59
-
60
- def time_diff_seconds(start_time: str, end_time: str, fmt: str = '%Y-%m-%d %H:%M:%S'):
61
- """
62
- 计算两个时间字符串之间的秒数差。
63
-
64
- :param start_time: 起始时间字符串
65
- :param end_time: 结束时间字符串
66
- :param fmt: 时间格式,默认为 '%Y-%m-%d %H:%M:%S'
67
- :return: 秒数差(总是正整数)
68
- """
69
- start = datetime.strptime(start_time, fmt)
70
- end = datetime.strptime(end_time, fmt)
71
- delta = end - start
72
- return int(delta.total_seconds())
73
-
74
-
75
- TimeType = Union[str, datetime]
76
-
77
-
78
- def time_diff(start: TimeType, end: TimeType, fmt: str = None, unit='seconds', auto_parse=True) -> Optional[int]:
79
- """
80
- 计算两个时间之间的差值(支持字符串或 datetime)。
81
-
82
- :param start: 起始时间(字符串或 datetime)
83
- :param end: 结束时间(字符串或 datetime)
84
- :param fmt: 时间格式(如果传入字符串且 auto_parse=False 时需要)
85
- :param unit: 单位(seconds, minutes, hours, days)
86
- :param auto_parse: 是否自动尝试解析任意格式的字符串(推荐开启)
87
- :return: 差值整数(根据 unit 返回),失败返回 None
88
- """
89
-
90
- def ensure_datetime(t):
91
- if isinstance(t, datetime):
92
- return t
93
- elif isinstance(t, str):
94
- if auto_parse:
95
- parsed = normalize_time(t)
96
- if parsed:
97
- return parsed
98
- if fmt:
99
- return datetime.strptime(t, fmt)
100
- raise ValueError("字符串时间未提供格式,或无法自动解析")
101
- else:
102
- raise TypeError(f"不支持的时间类型: {type(t)}")
103
-
104
- start_dt = ensure_datetime(start)
105
- end_dt = ensure_datetime(end)
106
-
107
- delta = (end_dt - start_dt)
108
- abs_seconds = int(abs(delta.total_seconds()))
109
-
110
- if unit == 'seconds':
111
- return abs_seconds
112
- elif unit == 'minutes':
113
- return abs_seconds // 60
114
- elif unit == 'hours':
115
- return abs_seconds // 3600
116
- elif unit == 'days':
117
- return abs_seconds // 86400
118
- else:
119
- raise ValueError(f"Unsupported unit: {unit}")
120
-
121
-
122
- def format_datetime(dt, fmt="%Y-%m-%d %H:%M:%S"):
123
- """格式化时间"""
124
- return dt.strftime(fmt)
125
-
126
-
127
- def parse_datetime(s, fmt="%Y-%m-%d %H:%M:%S"):
128
- """将字符串解析为 datetime 对象"""
129
- return datetime.strptime(s, fmt)
130
-
131
-
132
- def datetime_to_timestamp(dt):
133
- """将 datetime 转换为时间戳"""
134
- return dt.timestamp()
135
-
136
-
137
- def timestamp_to_datetime(ts):
138
- """将时间戳转换为 datetime"""
139
- return datetime.fromtimestamp(ts)
140
-
141
-
142
- def add_days(dt, days=0):
143
- """日期加减(天)"""
144
- return dt + timedelta(days=days)
145
-
146
-
147
- def add_months(dt, months=0):
148
- """日期加减(月)"""
149
- return dt + relativedelta(months=months)
150
-
151
-
152
- def days_between(dt1, dt2):
153
- """计算两个日期之间的天数差"""
154
- return abs((dt2 - dt1).days)
155
-
156
-
157
- def is_leap_year(year):
158
- """判断是否是闰年"""
159
- return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
160
-
161
-
162
- def parse_relative_time(time_str: str) -> str:
163
- """
164
- 解析相对时间字符串(如 "3分钟前"、"昨天")为 datetime 对象。
165
- """
166
- dt = dateparser.parse(time_str)
167
- return dt.isoformat()
168
-
169
-
170
- if __name__ == '__main__':
171
- print(normalize_time(parse_relative_time("30分钟前")))
172
- print(parse_relative_time("昨天"))
173
- print(parse_relative_time("10小时前"))
174
- print(parse_relative_time("1个月前"))
175
- print(parse_relative_time("10天前"))
176
- print(parse_relative_time("2024年1月1日"))
177
- print(parse_relative_time('2025年5月30日'))
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)