crawlo 1.1.0__py3-none-any.whl → 1.1.2__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 +34 -24
- crawlo/__version__.py +1 -1
- crawlo/cli.py +40 -40
- crawlo/commands/__init__.py +13 -13
- crawlo/commands/check.py +594 -155
- crawlo/commands/genspider.py +152 -111
- crawlo/commands/list.py +156 -119
- crawlo/commands/run.py +285 -170
- crawlo/commands/startproject.py +196 -101
- crawlo/commands/stats.py +188 -167
- crawlo/commands/utils.py +187 -0
- crawlo/config.py +280 -0
- crawlo/core/__init__.py +2 -2
- crawlo/core/engine.py +171 -158
- crawlo/core/enhanced_engine.py +190 -0
- crawlo/core/processor.py +40 -40
- crawlo/core/scheduler.py +162 -57
- crawlo/crawler.py +1028 -493
- crawlo/downloader/__init__.py +242 -78
- crawlo/downloader/aiohttp_downloader.py +212 -199
- crawlo/downloader/cffi_downloader.py +252 -277
- crawlo/downloader/httpx_downloader.py +257 -246
- crawlo/event.py +11 -11
- crawlo/exceptions.py +78 -78
- 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 +34 -34
- crawlo/filters/__init__.py +154 -37
- crawlo/filters/aioredis_filter.py +242 -150
- crawlo/filters/memory_filter.py +269 -202
- crawlo/items/__init__.py +23 -23
- crawlo/items/base.py +21 -21
- crawlo/items/fields.py +53 -53
- crawlo/items/items.py +104 -104
- 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 -135
- crawlo/middleware/proxy.py +248 -245
- 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 +125 -90
- crawlo/mode_manager.py +201 -0
- crawlo/network/__init__.py +21 -7
- crawlo/network/request.py +311 -203
- crawlo/network/response.py +269 -166
- crawlo/pipelines/__init__.py +13 -13
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/pipelines/mongo_pipeline.py +116 -116
- crawlo/pipelines/mysql_pipeline.py +195 -195
- crawlo/pipelines/pipeline_manager.py +56 -56
- crawlo/project.py +153 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +304 -0
- crawlo/queue/redis_priority_queue.py +192 -0
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +226 -169
- crawlo/settings/setting_manager.py +99 -99
- crawlo/spider/__init__.py +639 -129
- crawlo/stats_collector.py +59 -59
- crawlo/subscriber.py +106 -106
- crawlo/task_manager.py +30 -27
- crawlo/templates/crawlo.cfg.tmpl +10 -10
- crawlo/templates/project/__init__.py.tmpl +3 -3
- crawlo/templates/project/items.py.tmpl +17 -17
- crawlo/templates/project/middlewares.py.tmpl +87 -76
- crawlo/templates/project/pipelines.py.tmpl +336 -64
- crawlo/templates/project/run.py.tmpl +239 -0
- crawlo/templates/project/settings.py.tmpl +248 -54
- crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
- crawlo/templates/spider/spider.py.tmpl +178 -32
- crawlo/utils/__init__.py +7 -7
- crawlo/utils/controlled_spider_mixin.py +336 -0
- crawlo/utils/date_tools.py +233 -233
- crawlo/utils/db_helper.py +343 -343
- crawlo/utils/func_tools.py +82 -82
- crawlo/utils/large_scale_config.py +287 -0
- crawlo/utils/large_scale_helper.py +344 -0
- crawlo/utils/log.py +128 -128
- crawlo/utils/queue_helper.py +176 -0
- crawlo/utils/request.py +267 -267
- crawlo/utils/request_serializer.py +220 -0
- crawlo/utils/spider_loader.py +62 -62
- crawlo/utils/system.py +11 -11
- crawlo/utils/tools.py +4 -4
- crawlo/utils/url.py +39 -39
- crawlo-1.1.2.dist-info/METADATA +567 -0
- crawlo-1.1.2.dist-info/RECORD +108 -0
- examples/__init__.py +7 -0
- tests/__init__.py +7 -7
- tests/test_final_validation.py +154 -0
- tests/test_proxy_health_check.py +32 -32
- tests/test_proxy_middleware_integration.py +136 -136
- tests/test_proxy_providers.py +56 -56
- tests/test_proxy_stats.py +19 -19
- tests/test_proxy_strategies.py +59 -59
- tests/test_redis_config.py +29 -0
- tests/test_redis_queue.py +225 -0
- tests/test_request_serialization.py +71 -0
- tests/test_scheduler.py +242 -0
- crawlo/pipelines/mysql_batch_pipline.py +0 -273
- crawlo/utils/concurrency_manager.py +0 -125
- crawlo/utils/pqueue.py +0 -174
- crawlo/utils/project.py +0 -197
- crawlo-1.1.0.dist-info/METADATA +0 -49
- crawlo-1.1.0.dist-info/RECORD +0 -97
- examples/gxb/items.py +0 -36
- examples/gxb/run.py +0 -16
- examples/gxb/settings.py +0 -72
- examples/gxb/spider/__init__.py +0 -2
- examples/gxb/spider/miit_spider.py +0 -180
- examples/gxb/spider/telecom_device.py +0 -129
- {examples/gxb → crawlo/queue}/__init__.py +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
|
@@ -1,273 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
import asyncio
|
|
3
|
-
import aiomysql
|
|
4
|
-
from typing import Optional, List, Dict
|
|
5
|
-
from asyncmy import create_pool
|
|
6
|
-
from crawlo.utils.log import get_logger
|
|
7
|
-
from crawlo.exceptions import ItemDiscard
|
|
8
|
-
from crawlo.utils.tools import make_insert_sql, logger
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class AsyncmyMySQLPipeline:
|
|
12
|
-
def __init__(self, crawler):
|
|
13
|
-
self.crawler = crawler
|
|
14
|
-
self.settings = crawler.settings
|
|
15
|
-
self.logger = get_logger(self.__class__.__name__, self.settings.get('LOG_LEVEL'))
|
|
16
|
-
|
|
17
|
-
# 配置参数
|
|
18
|
-
self.table_name = (
|
|
19
|
-
self.settings.get('MYSQL_TABLE') or
|
|
20
|
-
getattr(crawler.spider, 'mysql_table', None) or
|
|
21
|
-
f"{crawler.spider.name}_items"
|
|
22
|
-
)
|
|
23
|
-
self.batch_size = self.settings.getint('MYSQL_BATCH_SIZE', 100)
|
|
24
|
-
self.flush_interval = self.settings.getfloat('MYSQL_FLUSH_INTERVAL', 3.0) # 秒
|
|
25
|
-
|
|
26
|
-
# 连接池相关
|
|
27
|
-
self._pool_lock = asyncio.Lock()
|
|
28
|
-
self._pool_initialized = False
|
|
29
|
-
self.pool = None
|
|
30
|
-
|
|
31
|
-
# 缓冲区与锁
|
|
32
|
-
self.items_buffer: List[Dict] = []
|
|
33
|
-
self.buffer_lock = asyncio.Lock()
|
|
34
|
-
|
|
35
|
-
# 后台任务
|
|
36
|
-
self.flush_task: Optional[asyncio.Task] = None
|
|
37
|
-
|
|
38
|
-
# 注册关闭事件
|
|
39
|
-
crawler.subscriber.subscribe(self.spider_closed, event='spider_closed')
|
|
40
|
-
|
|
41
|
-
@classmethod
|
|
42
|
-
def from_crawler(cls, crawler):
|
|
43
|
-
return cls(crawler)
|
|
44
|
-
|
|
45
|
-
async def _ensure_pool(self):
|
|
46
|
-
"""确保连接池已初始化(线程安全)"""
|
|
47
|
-
if self._pool_initialized:
|
|
48
|
-
return
|
|
49
|
-
|
|
50
|
-
async with self._pool_lock:
|
|
51
|
-
if not self._pool_initialized:
|
|
52
|
-
try:
|
|
53
|
-
self.pool = await create_pool(
|
|
54
|
-
host=self.settings.get('MYSQL_HOST', 'localhost'),
|
|
55
|
-
port=self.settings.get_int('MYSQL_PORT', 3306),
|
|
56
|
-
user=self.settings.get('MYSQL_USER', 'root'),
|
|
57
|
-
password=self.settings.get('MYSQL_PASSWORD', ''),
|
|
58
|
-
db=self.settings.get('MYSQL_DB', 'scrapy_db'),
|
|
59
|
-
minsize=self.settings.get_int('MYSQL_POOL_MIN', 3),
|
|
60
|
-
maxsize=self.settings.get_int('MYSQL_POOL_MAX', 10),
|
|
61
|
-
echo=self.settings.get_bool('MYSQL_ECHO', False)
|
|
62
|
-
)
|
|
63
|
-
self._pool_initialized = True
|
|
64
|
-
self.logger.debug(f"MySQL连接池初始化完成(表: {self.table_name})")
|
|
65
|
-
except Exception as e:
|
|
66
|
-
self.logger.error(f"MySQL连接池初始化失败: {e}")
|
|
67
|
-
raise
|
|
68
|
-
|
|
69
|
-
async def open_spider(self, spider):
|
|
70
|
-
"""爬虫启动时初始化后台刷新任务"""
|
|
71
|
-
await self._ensure_pool()
|
|
72
|
-
self.flush_task = asyncio.create_task(self._flush_loop())
|
|
73
|
-
|
|
74
|
-
async def _flush_loop(self):
|
|
75
|
-
"""后台循环:定期检查是否需要刷新缓冲区"""
|
|
76
|
-
while True:
|
|
77
|
-
await asyncio.sleep(self.flush_interval)
|
|
78
|
-
if len(self.items_buffer) > 0:
|
|
79
|
-
await self._flush_buffer()
|
|
80
|
-
|
|
81
|
-
async def _flush_buffer(self):
|
|
82
|
-
"""将缓冲区中的数据批量写入数据库"""
|
|
83
|
-
async with self.buffer_lock:
|
|
84
|
-
if not self.items_buffer:
|
|
85
|
-
return
|
|
86
|
-
|
|
87
|
-
items_to_insert = self.items_buffer.copy()
|
|
88
|
-
self.items_buffer.clear()
|
|
89
|
-
|
|
90
|
-
try:
|
|
91
|
-
await self._ensure_pool()
|
|
92
|
-
first_item = items_to_insert[0]
|
|
93
|
-
sql = make_insert_sql(table=self.table_name, data=first_item, many=True)
|
|
94
|
-
|
|
95
|
-
values = [list(item.values()) for item in items_to_insert]
|
|
96
|
-
|
|
97
|
-
async with self.pool.acquire() as conn:
|
|
98
|
-
async with conn.cursor() as cursor:
|
|
99
|
-
affected_rows = await cursor.executemany(sql, values)
|
|
100
|
-
await conn.commit()
|
|
101
|
-
|
|
102
|
-
spider_name = getattr(self.crawler.spider, 'name', 'unknown')
|
|
103
|
-
self.logger.info(f"批量插入 {affected_rows} 条记录到 {self.table_name}")
|
|
104
|
-
self.crawler.stats.inc_value('mysql/insert_success_batch', len(items_to_insert))
|
|
105
|
-
|
|
106
|
-
except Exception as e:
|
|
107
|
-
self.logger.error(f"批量插入失败: {e}")
|
|
108
|
-
self.crawler.stats.inc_value('mysql/insert_failed_batch', len(items_to_insert))
|
|
109
|
-
# 可选:重试或丢弃
|
|
110
|
-
raise ItemDiscard(f"批量插入失败: {e}")
|
|
111
|
-
|
|
112
|
-
async def process_item(self, item, spider, kwargs=None) -> dict:
|
|
113
|
-
"""将 item 添加到缓冲区,触发批量插入"""
|
|
114
|
-
item_dict = dict(item)
|
|
115
|
-
|
|
116
|
-
async with self.buffer_lock:
|
|
117
|
-
self.items_buffer.append(item_dict)
|
|
118
|
-
if len(self.items_buffer) >= self.batch_size:
|
|
119
|
-
# 达到批量阈值,立即刷新
|
|
120
|
-
await self._flush_buffer()
|
|
121
|
-
|
|
122
|
-
return item
|
|
123
|
-
|
|
124
|
-
async def spider_closed(self):
|
|
125
|
-
"""关闭爬虫时,确保所有剩余数据被写入"""
|
|
126
|
-
if self.flush_task:
|
|
127
|
-
self.flush_task.cancel()
|
|
128
|
-
try:
|
|
129
|
-
await self.flush_task
|
|
130
|
-
except asyncio.CancelledError:
|
|
131
|
-
pass
|
|
132
|
-
|
|
133
|
-
# 刷最后一批数据
|
|
134
|
-
if self.items_buffer:
|
|
135
|
-
await self._flush_buffer()
|
|
136
|
-
|
|
137
|
-
# 关闭连接池
|
|
138
|
-
if self.pool:
|
|
139
|
-
self.pool.close()
|
|
140
|
-
await self.pool.wait_closed()
|
|
141
|
-
self.logger.info("MySQL连接池已关闭")
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
class AiomysqlMySQLPipeline:
|
|
145
|
-
def __init__(self, crawler):
|
|
146
|
-
self.crawler = crawler
|
|
147
|
-
self.settings = crawler.settings
|
|
148
|
-
self.logger = get_logger(self.__class__.__name__, self.settings.get('LOG_LEVEL'))
|
|
149
|
-
|
|
150
|
-
# 配置
|
|
151
|
-
self.table_name = (
|
|
152
|
-
self.settings.get('MYSQL_TABLE') or
|
|
153
|
-
getattr(crawler.spider, 'mysql_table', None) or
|
|
154
|
-
f"{crawler.spider.name}_items"
|
|
155
|
-
)
|
|
156
|
-
self.batch_size = self.settings.getint('MYSQL_BATCH_SIZE', 100)
|
|
157
|
-
self.flush_interval = self.settings.getfloat('MYSQL_FLUSH_INTERVAL', 3.0)
|
|
158
|
-
|
|
159
|
-
# 连接池
|
|
160
|
-
self._pool_lock = asyncio.Lock()
|
|
161
|
-
self._pool_initialized = False
|
|
162
|
-
self.pool = None
|
|
163
|
-
|
|
164
|
-
# 缓冲
|
|
165
|
-
self.items_buffer: List[Dict] = []
|
|
166
|
-
self.buffer_lock = asyncio.Lock()
|
|
167
|
-
|
|
168
|
-
# 后台任务
|
|
169
|
-
self.flush_task: Optional[asyncio.Task] = None
|
|
170
|
-
|
|
171
|
-
crawler.subscriber.subscribe(self.spider_closed, event='spider_closed')
|
|
172
|
-
|
|
173
|
-
@classmethod
|
|
174
|
-
def create_instance(cls, crawler):
|
|
175
|
-
return cls(crawler)
|
|
176
|
-
|
|
177
|
-
async def _init_pool(self):
|
|
178
|
-
"""延迟初始化连接池(线程安全)"""
|
|
179
|
-
if self._pool_initialized:
|
|
180
|
-
return
|
|
181
|
-
|
|
182
|
-
async with self._pool_lock:
|
|
183
|
-
if not self._pool_initialized:
|
|
184
|
-
try:
|
|
185
|
-
self.pool = await aiomysql.create_pool(
|
|
186
|
-
host=self.settings.get('MYSQL_HOST', 'localhost'),
|
|
187
|
-
port=self.settings.getint('MYSQL_PORT', 3306),
|
|
188
|
-
user=self.settings.get('MYSQL_USER', 'root'),
|
|
189
|
-
password=self.settings.get('MYSQL_PASSWORD', ''),
|
|
190
|
-
db=self.settings.get('MYSQL_DB', 'scrapy_db'),
|
|
191
|
-
minsize=self.settings.getint('MYSQL_POOL_MIN', 3),
|
|
192
|
-
maxsize=self.settings.getint('MYSQL_POOL_MAX', 10),
|
|
193
|
-
cursorclass=aiomysql.DictCursor,
|
|
194
|
-
autocommit=False
|
|
195
|
-
)
|
|
196
|
-
self._pool_initialized = True
|
|
197
|
-
self.logger.debug(f"aiomysql连接池已初始化(表: {self.table_name})")
|
|
198
|
-
except Exception as e:
|
|
199
|
-
self.logger.error(f"aiomysql连接池初始化失败: {e}")
|
|
200
|
-
raise
|
|
201
|
-
|
|
202
|
-
async def open_spider(self, spider):
|
|
203
|
-
"""爬虫启动时创建后台刷新任务"""
|
|
204
|
-
await self._init_pool()
|
|
205
|
-
self.flush_task = asyncio.create_task(self._flush_loop())
|
|
206
|
-
|
|
207
|
-
async def _flush_loop(self):
|
|
208
|
-
"""定期刷新缓冲区"""
|
|
209
|
-
while True:
|
|
210
|
-
await asyncio.sleep(self.flush_interval)
|
|
211
|
-
if len(self.items_buffer) > 0:
|
|
212
|
-
await self._flush_buffer()
|
|
213
|
-
|
|
214
|
-
async def _flush_buffer(self):
|
|
215
|
-
"""执行批量插入"""
|
|
216
|
-
async with self.buffer_lock:
|
|
217
|
-
if not self.items_buffer:
|
|
218
|
-
return
|
|
219
|
-
items_to_insert = self.items_buffer.copy()
|
|
220
|
-
self.items_buffer.clear()
|
|
221
|
-
|
|
222
|
-
try:
|
|
223
|
-
await self._init_pool()
|
|
224
|
-
keys = items_to_insert[0].keys()
|
|
225
|
-
placeholders = ', '.join(['%s'] * len(keys))
|
|
226
|
-
columns = ', '.join([f'`{k}`' for k in keys])
|
|
227
|
-
sql = f"INSERT INTO `{self.table_name}` ({columns}) VALUES ({placeholders})"
|
|
228
|
-
|
|
229
|
-
values = [list(item.values()) for item in items_to_insert]
|
|
230
|
-
|
|
231
|
-
async with self.pool.acquire() as conn:
|
|
232
|
-
async with conn.cursor() as cursor:
|
|
233
|
-
result = await cursor.executemany(sql, values)
|
|
234
|
-
await conn.commit()
|
|
235
|
-
|
|
236
|
-
spider_name = getattr(self.crawler.spider, 'name', 'unknown')
|
|
237
|
-
self.logger.info(f"【{spider_name}】批量插入 {result} 条记录到 {self.table_name}")
|
|
238
|
-
self.crawler.stats.inc_value('mysql/insert_success_batch', len(items_to_insert))
|
|
239
|
-
|
|
240
|
-
except aiomysql.Error as e:
|
|
241
|
-
self.logger.error(f"aiomysql批量插入失败: {e}")
|
|
242
|
-
self.crawler.stats.inc_value('mysql/insert_failed_batch', len(items_to_insert))
|
|
243
|
-
raise ItemDiscard(f"MySQL错误: {e.args[1]}")
|
|
244
|
-
except Exception as e:
|
|
245
|
-
self.logger.error(f"未知错误: {e}")
|
|
246
|
-
raise ItemDiscard(f"处理失败: {e}")
|
|
247
|
-
|
|
248
|
-
async def process_item(self, item, spider) -> dict:
|
|
249
|
-
item_dict = dict(item)
|
|
250
|
-
|
|
251
|
-
async with self.buffer_lock:
|
|
252
|
-
self.items_buffer.append(item_dict)
|
|
253
|
-
if len(self.items_buffer) >= self.batch_size:
|
|
254
|
-
await self._flush_buffer()
|
|
255
|
-
|
|
256
|
-
return item
|
|
257
|
-
|
|
258
|
-
async def spider_closed(self):
|
|
259
|
-
"""清理资源并提交剩余数据"""
|
|
260
|
-
if self.flush_task:
|
|
261
|
-
self.flush_task.cancel()
|
|
262
|
-
try:
|
|
263
|
-
await self.flush_task
|
|
264
|
-
except asyncio.CancelledError:
|
|
265
|
-
pass
|
|
266
|
-
|
|
267
|
-
if self.items_buffer:
|
|
268
|
-
await self._flush_buffer()
|
|
269
|
-
|
|
270
|
-
if self.pool:
|
|
271
|
-
self.pool.close()
|
|
272
|
-
await self.pool.wait_closed()
|
|
273
|
-
self.logger.info("aiomysql连接池已释放")
|
|
@@ -1,125 +0,0 @@
|
|
|
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
|
-
return min(50, cpu_count * 5) # 保守的默认计算方式
|
crawlo/utils/pqueue.py
DELETED
|
@@ -1,174 +0,0 @@
|
|
|
1
|
-
# -*- coding:UTF-8 -*-
|
|
2
|
-
import sys
|
|
3
|
-
import asyncio
|
|
4
|
-
import warnings
|
|
5
|
-
from urllib.parse import urlparse
|
|
6
|
-
from asyncio import PriorityQueue
|
|
7
|
-
from redis.asyncio import from_url
|
|
8
|
-
from typing import Any, Optional, Dict, Annotated
|
|
9
|
-
from pydantic import (
|
|
10
|
-
BaseModel,
|
|
11
|
-
Field,
|
|
12
|
-
model_validator
|
|
13
|
-
)
|
|
14
|
-
|
|
15
|
-
from crawlo import Request
|
|
16
|
-
from crawlo.settings.default_settings import REDIS_URL
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class SpiderPriorityQueue(PriorityQueue):
|
|
20
|
-
"""带超时功能的异步优先级队列"""
|
|
21
|
-
|
|
22
|
-
def __init__(self, maxsize: int = 0) -> None:
|
|
23
|
-
"""初始化队列,maxsize为0表示无大小限制"""
|
|
24
|
-
super().__init__(maxsize)
|
|
25
|
-
|
|
26
|
-
async def get(self, timeout: float = 0.1) -> Optional[Request]:
|
|
27
|
-
"""
|
|
28
|
-
异步获取队列元素,带超时功能
|
|
29
|
-
|
|
30
|
-
Args:
|
|
31
|
-
timeout: 超时时间(秒),默认0.1秒
|
|
32
|
-
|
|
33
|
-
Returns:
|
|
34
|
-
队列元素(优先级, 值)或None(超时)
|
|
35
|
-
"""
|
|
36
|
-
try:
|
|
37
|
-
# 根据Python版本选择超时实现方式
|
|
38
|
-
if sys.version_info >= (3, 11):
|
|
39
|
-
async with asyncio.timeout(timeout):
|
|
40
|
-
return await super().get()
|
|
41
|
-
else:
|
|
42
|
-
return await asyncio.wait_for(super().get(), timeout=timeout)
|
|
43
|
-
except asyncio.TimeoutError:
|
|
44
|
-
return None
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
class TaskModel(BaseModel):
|
|
48
|
-
"""爬虫任务数据模型 (完全兼容Pydantic V2)"""
|
|
49
|
-
url: Annotated[str, Field(min_length=1, max_length=2000, examples=["https://example.com"])]
|
|
50
|
-
meta: Dict[str, Any] = Field(default_factory=dict)
|
|
51
|
-
priority: Annotated[int, Field(default=0, ge=0, le=10, description="0=最高优先级")]
|
|
52
|
-
|
|
53
|
-
@classmethod
|
|
54
|
-
def validate_url(cls, v: str) -> str:
|
|
55
|
-
"""验证URL格式"""
|
|
56
|
-
if not v.startswith(('http://', 'https://')):
|
|
57
|
-
raise ValueError('URL必须以 http:// 或 https:// 开头')
|
|
58
|
-
|
|
59
|
-
parsed = urlparse(v)
|
|
60
|
-
if not parsed.netloc:
|
|
61
|
-
raise ValueError('URL缺少有效域名')
|
|
62
|
-
|
|
63
|
-
return v.strip()
|
|
64
|
-
|
|
65
|
-
@model_validator(mode='after')
|
|
66
|
-
def validate_priority_logic(self) -> 'TaskModel':
|
|
67
|
-
"""跨字段验证示例"""
|
|
68
|
-
if 'admin' in self.url and self.priority > 5:
|
|
69
|
-
self.priority = 5 # 自动调整管理页面的优先级
|
|
70
|
-
return self
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
class DistributedPriorityQueue:
|
|
74
|
-
def __init__(
|
|
75
|
-
self,
|
|
76
|
-
redis_url: str,
|
|
77
|
-
queue_name: str = "spider_queue",
|
|
78
|
-
max_connections: int = 10,
|
|
79
|
-
health_check_interval: int = 30
|
|
80
|
-
):
|
|
81
|
-
"""
|
|
82
|
-
Args:
|
|
83
|
-
redis_url: redis://[:password]@host:port[/db]
|
|
84
|
-
queue_name: Redis有序集合键名
|
|
85
|
-
max_connections: 连接池大小
|
|
86
|
-
health_check_interval: 连接健康检查间隔(秒)
|
|
87
|
-
"""
|
|
88
|
-
self.redis = from_url(
|
|
89
|
-
redis_url,
|
|
90
|
-
max_connections=max_connections,
|
|
91
|
-
health_check_interval=health_check_interval,
|
|
92
|
-
socket_keepalive=True,
|
|
93
|
-
decode_responses=True
|
|
94
|
-
)
|
|
95
|
-
self.queue_name = queue_name
|
|
96
|
-
|
|
97
|
-
async def put(self, task: TaskModel) -> bool:
|
|
98
|
-
"""
|
|
99
|
-
添加任务到队列(使用Pydantic V2的model_dump_json)
|
|
100
|
-
|
|
101
|
-
Args:
|
|
102
|
-
task: 已验证的TaskModel实例
|
|
103
|
-
|
|
104
|
-
Returns:
|
|
105
|
-
bool: 是否成功添加 (Redis的ZADD返回添加数量)
|
|
106
|
-
"""
|
|
107
|
-
with warnings.catch_warnings():
|
|
108
|
-
warnings.simplefilter("ignore", category=DeprecationWarning)
|
|
109
|
-
task_str = task.model_dump_json() # 正确使用V2的序列化方法
|
|
110
|
-
return await self.redis.zadd(
|
|
111
|
-
self.queue_name,
|
|
112
|
-
{task_str: task.priority}
|
|
113
|
-
) > 0
|
|
114
|
-
|
|
115
|
-
async def get(self, timeout: float = 1.0) -> Optional[TaskModel]:
|
|
116
|
-
"""
|
|
117
|
-
获取优先级最高的任务(自动验证)
|
|
118
|
-
|
|
119
|
-
Args:
|
|
120
|
-
timeout: 阻塞超时时间(秒)
|
|
121
|
-
|
|
122
|
-
Returns:
|
|
123
|
-
TaskModel实例或None(超时/队列空)
|
|
124
|
-
"""
|
|
125
|
-
try:
|
|
126
|
-
result = await self.redis.bzpopmax(
|
|
127
|
-
self.queue_name,
|
|
128
|
-
timeout=timeout
|
|
129
|
-
)
|
|
130
|
-
if result:
|
|
131
|
-
_, task_str, _ = result
|
|
132
|
-
with warnings.catch_warnings():
|
|
133
|
-
warnings.simplefilter("ignore", category=DeprecationWarning)
|
|
134
|
-
return TaskModel.model_validate_json(task_str) # 正确使用V2的反序列化方法
|
|
135
|
-
except Exception as e:
|
|
136
|
-
print(f"任务获取失败: {type(e).__name__}: {e}")
|
|
137
|
-
return None
|
|
138
|
-
|
|
139
|
-
async def aclose(self):
|
|
140
|
-
"""安全关闭连接"""
|
|
141
|
-
await self.redis.aclose()
|
|
142
|
-
|
|
143
|
-
async def __aenter__(self):
|
|
144
|
-
return self
|
|
145
|
-
|
|
146
|
-
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
147
|
-
await self.aclose()
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
# 使用示例
|
|
151
|
-
async def demo():
|
|
152
|
-
async with DistributedPriorityQueue(
|
|
153
|
-
REDIS_URL,
|
|
154
|
-
max_connections=20,
|
|
155
|
-
health_check_interval=10
|
|
156
|
-
) as queue:
|
|
157
|
-
# 添加任务(自动触发验证)
|
|
158
|
-
task = TaskModel(
|
|
159
|
-
url="https://example.com/1",
|
|
160
|
-
priority=1,
|
|
161
|
-
meta={"depth": 2}
|
|
162
|
-
)
|
|
163
|
-
|
|
164
|
-
if await queue.put(task):
|
|
165
|
-
print(f"任务添加成功: {task.url}")
|
|
166
|
-
|
|
167
|
-
# 获取任务
|
|
168
|
-
if result := await queue.get(timeout=2.0):
|
|
169
|
-
print(f"获取任务: {result.url} (优先级={result.priority})")
|
|
170
|
-
print(f"元数据: {result.meta}")
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if __name__ == "__main__":
|
|
174
|
-
asyncio.run(demo())
|