crawlo 1.1.1__py3-none-any.whl → 1.1.3__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 -33
- crawlo/__version__.py +1 -1
- crawlo/cli.py +40 -40
- crawlo/commands/__init__.py +13 -13
- crawlo/commands/check.py +594 -594
- crawlo/commands/genspider.py +152 -126
- crawlo/commands/list.py +156 -147
- crawlo/commands/run.py +285 -285
- crawlo/commands/startproject.py +196 -111
- crawlo/commands/stats.py +188 -188
- 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 +166 -57
- crawlo/crawler.py +1028 -495
- crawlo/downloader/__init__.py +242 -78
- crawlo/downloader/aiohttp_downloader.py +212 -199
- crawlo/downloader/cffi_downloader.py +251 -241
- crawlo/downloader/httpx_downloader.py +259 -246
- crawlo/event.py +11 -11
- crawlo/exceptions.py +82 -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 +271 -166
- crawlo/pipelines/__init__.py +22 -13
- crawlo/pipelines/bloom_dedup_pipeline.py +157 -0
- crawlo/pipelines/console_pipeline.py +39 -39
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/database_dedup_pipeline.py +225 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/pipelines/memory_dedup_pipeline.py +116 -0
- crawlo/pipelines/mongo_pipeline.py +116 -116
- crawlo/pipelines/mysql_pipeline.py +195 -195
- crawlo/pipelines/pipeline_manager.py +56 -56
- crawlo/pipelines/redis_dedup_pipeline.py +163 -0
- crawlo/project.py +153 -153
- crawlo/queue/__init__.py +0 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +308 -0
- crawlo/queue/redis_priority_queue.py +209 -0
- crawlo/settings/__init__.py +7 -7
- crawlo/settings/default_settings.py +245 -167
- 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 +342 -64
- crawlo/templates/project/run.py.tmpl +252 -0
- crawlo/templates/project/settings.py.tmpl +251 -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 +440 -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.3.dist-info/METADATA +635 -0
- crawlo-1.1.3.dist-info/RECORD +113 -0
- examples/__init__.py +7 -7
- examples/controlled_spider_example.py +205 -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/pqueue.py +0 -174
- crawlo-1.1.1.dist-info/METADATA +0 -220
- crawlo-1.1.1.dist-info/RECORD +0 -100
- examples/baidu_spider/__init__.py +0 -7
- examples/baidu_spider/demo.py +0 -94
- examples/baidu_spider/items.py +0 -46
- examples/baidu_spider/middleware.py +0 -49
- examples/baidu_spider/pipeline.py +0 -55
- examples/baidu_spider/run.py +0 -27
- examples/baidu_spider/settings.py +0 -121
- examples/baidu_spider/spiders/__init__.py +0 -7
- examples/baidu_spider/spiders/bai_du.py +0 -61
- examples/baidu_spider/spiders/miit.py +0 -159
- examples/baidu_spider/spiders/sina.py +0 -79
- {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/WHEEL +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
增强的引擎实现
|
|
5
|
+
解决大规模请求生成时的并发控制和背压问题
|
|
6
|
+
"""
|
|
7
|
+
import asyncio
|
|
8
|
+
|
|
9
|
+
from crawlo.core.engine import Engine as BaseEngine
|
|
10
|
+
from crawlo.utils.log import get_logger
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class EnhancedEngine(BaseEngine):
|
|
14
|
+
"""
|
|
15
|
+
增强的引擎实现
|
|
16
|
+
|
|
17
|
+
主要改进:
|
|
18
|
+
1. 智能的请求生成控制
|
|
19
|
+
2. 背压感知的调度
|
|
20
|
+
3. 动态并发调整
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, crawler):
|
|
24
|
+
super().__init__(crawler)
|
|
25
|
+
|
|
26
|
+
# 增强控制参数
|
|
27
|
+
self.max_queue_size = self.settings.get_int('SCHEDULER_MAX_QUEUE_SIZE', 200)
|
|
28
|
+
self.generation_batch_size = 10
|
|
29
|
+
self.generation_interval = 0.05
|
|
30
|
+
self.backpressure_ratio = 0.8 # 队列达到80%时启动背压
|
|
31
|
+
|
|
32
|
+
# 状态跟踪
|
|
33
|
+
self._generation_paused = False
|
|
34
|
+
self._last_generation_time = 0
|
|
35
|
+
self._generation_stats = {
|
|
36
|
+
'total_generated': 0,
|
|
37
|
+
'backpressure_events': 0
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
41
|
+
|
|
42
|
+
async def crawl(self):
|
|
43
|
+
"""
|
|
44
|
+
增强的爬取循环
|
|
45
|
+
支持智能请求生成和背压控制
|
|
46
|
+
"""
|
|
47
|
+
generation_task = None
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
# 启动请求生成任务
|
|
51
|
+
if self.start_requests:
|
|
52
|
+
generation_task = asyncio.create_task(
|
|
53
|
+
self._controlled_request_generation()
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# 主爬取循环
|
|
57
|
+
while self.running:
|
|
58
|
+
# 获取并处理请求
|
|
59
|
+
if request := await self._get_next_request():
|
|
60
|
+
await self._crawl(request)
|
|
61
|
+
|
|
62
|
+
# 检查退出条件
|
|
63
|
+
if await self._should_exit():
|
|
64
|
+
break
|
|
65
|
+
|
|
66
|
+
# 短暂休息避免忙等
|
|
67
|
+
await asyncio.sleep(0.001)
|
|
68
|
+
|
|
69
|
+
finally:
|
|
70
|
+
# 清理生成任务
|
|
71
|
+
if generation_task and not generation_task.done():
|
|
72
|
+
generation_task.cancel()
|
|
73
|
+
try:
|
|
74
|
+
await generation_task
|
|
75
|
+
except asyncio.CancelledError:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
await self.close_spider()
|
|
79
|
+
|
|
80
|
+
async def _controlled_request_generation(self):
|
|
81
|
+
"""受控的请求生成"""
|
|
82
|
+
self.logger.info("🎛️ 启动受控请求生成")
|
|
83
|
+
|
|
84
|
+
batch = []
|
|
85
|
+
total_generated = 0
|
|
86
|
+
|
|
87
|
+
try:
|
|
88
|
+
for request in self.start_requests:
|
|
89
|
+
batch.append(request)
|
|
90
|
+
|
|
91
|
+
# 批量处理
|
|
92
|
+
if len(batch) >= self.generation_batch_size:
|
|
93
|
+
generated = await self._process_generation_batch(batch)
|
|
94
|
+
total_generated += generated
|
|
95
|
+
batch = []
|
|
96
|
+
|
|
97
|
+
# 背压检查
|
|
98
|
+
if await self._should_pause_generation():
|
|
99
|
+
await self._wait_for_capacity()
|
|
100
|
+
|
|
101
|
+
# 处理剩余请求
|
|
102
|
+
if batch:
|
|
103
|
+
generated = await self._process_generation_batch(batch)
|
|
104
|
+
total_generated += generated
|
|
105
|
+
|
|
106
|
+
except Exception as e:
|
|
107
|
+
self.logger.error(f"❌ 请求生成失败: {e}")
|
|
108
|
+
|
|
109
|
+
finally:
|
|
110
|
+
self.start_requests = None
|
|
111
|
+
self.logger.info(f"🎉 请求生成完成,总计: {total_generated}")
|
|
112
|
+
|
|
113
|
+
async def _process_generation_batch(self, batch) -> int:
|
|
114
|
+
"""处理一批请求"""
|
|
115
|
+
generated = 0
|
|
116
|
+
|
|
117
|
+
for request in batch:
|
|
118
|
+
if not self.running:
|
|
119
|
+
break
|
|
120
|
+
|
|
121
|
+
# 等待队列有空间
|
|
122
|
+
while await self._is_queue_full() and self.running:
|
|
123
|
+
await asyncio.sleep(0.1)
|
|
124
|
+
|
|
125
|
+
if self.running:
|
|
126
|
+
await self.enqueue_request(request)
|
|
127
|
+
generated += 1
|
|
128
|
+
self._generation_stats['total_generated'] += 1
|
|
129
|
+
|
|
130
|
+
# 控制生成速度
|
|
131
|
+
if self.generation_interval > 0:
|
|
132
|
+
await asyncio.sleep(self.generation_interval)
|
|
133
|
+
|
|
134
|
+
return generated
|
|
135
|
+
|
|
136
|
+
async def _should_pause_generation(self) -> bool:
|
|
137
|
+
"""判断是否应该暂停生成"""
|
|
138
|
+
# 检查队列大小
|
|
139
|
+
if await self._is_queue_full():
|
|
140
|
+
return True
|
|
141
|
+
|
|
142
|
+
# 检查任务管理器负载
|
|
143
|
+
if self.task_manager:
|
|
144
|
+
current_tasks = len(self.task_manager.current_task)
|
|
145
|
+
if hasattr(self.task_manager, 'semaphore'):
|
|
146
|
+
max_concurrency = getattr(self.task_manager.semaphore, '_initial_value', 8)
|
|
147
|
+
if current_tasks >= max_concurrency * self.backpressure_ratio:
|
|
148
|
+
return True
|
|
149
|
+
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
async def _is_queue_full(self) -> bool:
|
|
153
|
+
"""检查队列是否已满"""
|
|
154
|
+
if not self.scheduler:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
queue_size = len(self.scheduler)
|
|
158
|
+
return queue_size >= self.max_queue_size * self.backpressure_ratio
|
|
159
|
+
|
|
160
|
+
async def _wait_for_capacity(self):
|
|
161
|
+
"""等待系统有足够容量"""
|
|
162
|
+
self._generation_stats['backpressure_events'] += 1
|
|
163
|
+
self.logger.debug("⏸️ 触发背压,暂停请求生成")
|
|
164
|
+
|
|
165
|
+
wait_time = 0.1
|
|
166
|
+
max_wait = 2.0
|
|
167
|
+
|
|
168
|
+
while await self._should_pause_generation() and self.running:
|
|
169
|
+
await asyncio.sleep(wait_time)
|
|
170
|
+
wait_time = min(wait_time * 1.1, max_wait)
|
|
171
|
+
|
|
172
|
+
async def _should_exit(self) -> bool:
|
|
173
|
+
"""检查是否应该退出"""
|
|
174
|
+
# 没有启动请求,且所有队列都空闲
|
|
175
|
+
if (self.start_requests is None and
|
|
176
|
+
self.scheduler.idle() and
|
|
177
|
+
self.downloader.idle() and
|
|
178
|
+
self.task_manager.all_done() and
|
|
179
|
+
self.processor.idle()):
|
|
180
|
+
return True
|
|
181
|
+
|
|
182
|
+
return False
|
|
183
|
+
|
|
184
|
+
def get_generation_stats(self) -> dict:
|
|
185
|
+
"""获取生成统计"""
|
|
186
|
+
return {
|
|
187
|
+
**self._generation_stats,
|
|
188
|
+
'queue_size': len(self.scheduler) if self.scheduler else 0,
|
|
189
|
+
'active_tasks': len(self.task_manager.current_task) if self.task_manager else 0
|
|
190
|
+
}
|
crawlo/core/processor.py
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
from asyncio import Queue
|
|
4
|
-
from typing import Union, Optional
|
|
5
|
-
|
|
6
|
-
from crawlo import Request, Item
|
|
7
|
-
from crawlo.pipelines.pipeline_manager import PipelineManager
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class Processor(object):
|
|
11
|
-
|
|
12
|
-
def __init__(self, crawler):
|
|
13
|
-
self.crawler = crawler
|
|
14
|
-
self.queue: Queue = Queue()
|
|
15
|
-
self.pipelines: Optional[PipelineManager] = None
|
|
16
|
-
|
|
17
|
-
def open(self):
|
|
18
|
-
self.pipelines = PipelineManager.from_crawler(self.crawler)
|
|
19
|
-
|
|
20
|
-
async def process(self):
|
|
21
|
-
while not self.idle():
|
|
22
|
-
result = await self.queue.get()
|
|
23
|
-
if isinstance(result, Request):
|
|
24
|
-
await self.crawler.engine.enqueue_request(result)
|
|
25
|
-
else:
|
|
26
|
-
assert isinstance(result, Item)
|
|
27
|
-
await self._process_item(result)
|
|
28
|
-
|
|
29
|
-
async def _process_item(self, item):
|
|
30
|
-
await self.pipelines.process_item(item=item)
|
|
31
|
-
|
|
32
|
-
async def enqueue(self, output: Union[Request, Item]):
|
|
33
|
-
await self.queue.put(output)
|
|
34
|
-
await self.process()
|
|
35
|
-
|
|
36
|
-
def idle(self) -> bool:
|
|
37
|
-
return len(self) == 0
|
|
38
|
-
|
|
39
|
-
def __len__(self):
|
|
40
|
-
return self.queue.qsize()
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
from asyncio import Queue
|
|
4
|
+
from typing import Union, Optional
|
|
5
|
+
|
|
6
|
+
from crawlo import Request, Item
|
|
7
|
+
from crawlo.pipelines.pipeline_manager import PipelineManager
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Processor(object):
|
|
11
|
+
|
|
12
|
+
def __init__(self, crawler):
|
|
13
|
+
self.crawler = crawler
|
|
14
|
+
self.queue: Queue = Queue()
|
|
15
|
+
self.pipelines: Optional[PipelineManager] = None
|
|
16
|
+
|
|
17
|
+
def open(self):
|
|
18
|
+
self.pipelines = PipelineManager.from_crawler(self.crawler)
|
|
19
|
+
|
|
20
|
+
async def process(self):
|
|
21
|
+
while not self.idle():
|
|
22
|
+
result = await self.queue.get()
|
|
23
|
+
if isinstance(result, Request):
|
|
24
|
+
await self.crawler.engine.enqueue_request(result)
|
|
25
|
+
else:
|
|
26
|
+
assert isinstance(result, Item)
|
|
27
|
+
await self._process_item(result)
|
|
28
|
+
|
|
29
|
+
async def _process_item(self, item):
|
|
30
|
+
await self.pipelines.process_item(item=item)
|
|
31
|
+
|
|
32
|
+
async def enqueue(self, output: Union[Request, Item]):
|
|
33
|
+
await self.queue.put(output)
|
|
34
|
+
await self.process()
|
|
35
|
+
|
|
36
|
+
def idle(self) -> bool:
|
|
37
|
+
return len(self) == 0
|
|
38
|
+
|
|
39
|
+
def __len__(self):
|
|
40
|
+
return self.queue.qsize()
|
crawlo/core/scheduler.py
CHANGED
|
@@ -1,57 +1,166 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
from typing import Optional, Callable
|
|
4
|
-
|
|
5
|
-
from crawlo.utils.log import get_logger
|
|
6
|
-
from crawlo.utils.request import set_request
|
|
7
|
-
from crawlo.utils.
|
|
8
|
-
from crawlo.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
self.
|
|
15
|
-
|
|
16
|
-
self.
|
|
17
|
-
|
|
18
|
-
self.
|
|
19
|
-
self.
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
from typing import Optional, Callable
|
|
4
|
+
|
|
5
|
+
from crawlo.utils.log import get_logger
|
|
6
|
+
from crawlo.utils.request import set_request
|
|
7
|
+
from crawlo.utils.request_serializer import RequestSerializer
|
|
8
|
+
from crawlo.queue.queue_manager import QueueManager, QueueConfig
|
|
9
|
+
from crawlo.project import load_class, common_call
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Scheduler:
|
|
13
|
+
def __init__(self, crawler, dupe_filter, stats, log_level, priority):
|
|
14
|
+
self.crawler = crawler
|
|
15
|
+
self.queue_manager: Optional[QueueManager] = None
|
|
16
|
+
self.request_serializer = RequestSerializer() # 专门处理序列化
|
|
17
|
+
|
|
18
|
+
self.logger = get_logger(name=self.__class__.__name__, level=log_level)
|
|
19
|
+
self.stats = stats
|
|
20
|
+
self.dupe_filter = dupe_filter
|
|
21
|
+
self.priority = priority
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def create_instance(cls, crawler):
|
|
25
|
+
filter_cls = load_class(crawler.settings.get('FILTER_CLASS'))
|
|
26
|
+
o = cls(
|
|
27
|
+
crawler=crawler,
|
|
28
|
+
dupe_filter=filter_cls.create_instance(crawler),
|
|
29
|
+
stats=crawler.stats,
|
|
30
|
+
log_level=crawler.settings.get('LOG_LEVEL'),
|
|
31
|
+
priority=crawler.settings.get('DEPTH_PRIORITY')
|
|
32
|
+
)
|
|
33
|
+
return o
|
|
34
|
+
|
|
35
|
+
async def open(self):
|
|
36
|
+
"""初始化调度器和队列"""
|
|
37
|
+
try:
|
|
38
|
+
# 创建队列配置
|
|
39
|
+
queue_config = QueueConfig.from_settings(self.crawler.settings)
|
|
40
|
+
|
|
41
|
+
# 创建队列管理器
|
|
42
|
+
self.queue_manager = QueueManager(queue_config)
|
|
43
|
+
|
|
44
|
+
# 初始化队列
|
|
45
|
+
success = await self.queue_manager.initialize()
|
|
46
|
+
if not success:
|
|
47
|
+
raise RuntimeError("队列初始化失败")
|
|
48
|
+
|
|
49
|
+
# 输出队列状态
|
|
50
|
+
status = self.queue_manager.get_status()
|
|
51
|
+
self.logger.info(f'队列类型: {status["type"]}, 状态: {status["health"]}')
|
|
52
|
+
self.logger.info(f'requesting filter: {self.dupe_filter}')
|
|
53
|
+
except Exception as e:
|
|
54
|
+
self.logger.error(f"❌ 调度器初始化失败: {e}")
|
|
55
|
+
raise
|
|
56
|
+
|
|
57
|
+
async def next_request(self):
|
|
58
|
+
"""获取下一个请求"""
|
|
59
|
+
if not self.queue_manager:
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
request = await self.queue_manager.get()
|
|
63
|
+
|
|
64
|
+
# 恢复 callback(从 Redis 队列取出时)
|
|
65
|
+
if request:
|
|
66
|
+
spider = getattr(self.crawler, 'spider', None)
|
|
67
|
+
request = self.request_serializer.restore_after_deserialization(request, spider)
|
|
68
|
+
|
|
69
|
+
return request
|
|
70
|
+
|
|
71
|
+
async def enqueue_request(self, request):
|
|
72
|
+
"""将请求加入队列"""
|
|
73
|
+
if not request.dont_filter and await common_call(self.dupe_filter.requested, request):
|
|
74
|
+
self.dupe_filter.log_stats(request)
|
|
75
|
+
return False
|
|
76
|
+
|
|
77
|
+
if not self.queue_manager:
|
|
78
|
+
self.logger.error("队列管理器未初始化")
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
set_request(request, self.priority)
|
|
82
|
+
|
|
83
|
+
# 使用统一的队列接口
|
|
84
|
+
success = await self.queue_manager.put(request, priority=getattr(request, 'priority', 0))
|
|
85
|
+
|
|
86
|
+
if success:
|
|
87
|
+
self.logger.debug(f"✅ 请求入队成功: {request.url}")
|
|
88
|
+
|
|
89
|
+
return success
|
|
90
|
+
|
|
91
|
+
def idle(self) -> bool:
|
|
92
|
+
"""检查队列是否为空"""
|
|
93
|
+
return len(self) == 0
|
|
94
|
+
|
|
95
|
+
async def close(self):
|
|
96
|
+
"""关闭调度器"""
|
|
97
|
+
if isinstance(closed := getattr(self.dupe_filter, 'closed', None), Callable):
|
|
98
|
+
await closed()
|
|
99
|
+
|
|
100
|
+
if self.queue_manager:
|
|
101
|
+
await self.queue_manager.close()
|
|
102
|
+
|
|
103
|
+
def __len__(self):
|
|
104
|
+
"""获取队列大小"""
|
|
105
|
+
if not self.queue_manager:
|
|
106
|
+
return 0
|
|
107
|
+
# 返回同步的近似值,实际大小需要异步获取
|
|
108
|
+
return 0 if self.queue_manager.empty() else 1
|
|
109
|
+
|
|
110
|
+
# #!/usr/bin/python
|
|
111
|
+
# # -*- coding:UTF-8 -*-
|
|
112
|
+
# from typing import Optional, Callable
|
|
113
|
+
#
|
|
114
|
+
# from crawlo.utils.log import get_logger
|
|
115
|
+
# from crawlo.utils.request import set_request
|
|
116
|
+
# from crawlo.utils.pqueue import SpiderPriorityQueue
|
|
117
|
+
# from crawlo.project import load_class, common_call
|
|
118
|
+
#
|
|
119
|
+
#
|
|
120
|
+
# class Scheduler:
|
|
121
|
+
# def __init__(self, crawler, dupe_filter, stats, log_level, priority):
|
|
122
|
+
# self.crawler = crawler
|
|
123
|
+
# self.request_queue: Optional[SpiderPriorityQueue] = None
|
|
124
|
+
#
|
|
125
|
+
# self.logger = get_logger(name=self.__class__.__name__, level=log_level)
|
|
126
|
+
# self.stats = stats
|
|
127
|
+
# self.dupe_filter = dupe_filter
|
|
128
|
+
# self.priority = priority
|
|
129
|
+
#
|
|
130
|
+
# @classmethod
|
|
131
|
+
# def create_instance(cls, crawler):
|
|
132
|
+
# filter_cls = load_class(crawler.settings.get('FILTER_CLASS'))
|
|
133
|
+
# o = cls(
|
|
134
|
+
# crawler=crawler,
|
|
135
|
+
# dupe_filter=filter_cls.create_instance(crawler),
|
|
136
|
+
# stats=crawler.stats,
|
|
137
|
+
# log_level=crawler.settings.get('LOG_LEVEL'),
|
|
138
|
+
# priority=crawler.settings.get('DEPTH_PRIORITY')
|
|
139
|
+
# )
|
|
140
|
+
# return o
|
|
141
|
+
#
|
|
142
|
+
# def open(self):
|
|
143
|
+
# self.request_queue = SpiderPriorityQueue()
|
|
144
|
+
# self.logger.info(f'requesting filter: {self.dupe_filter}')
|
|
145
|
+
#
|
|
146
|
+
# async def next_request(self):
|
|
147
|
+
# request = await self.request_queue.get()
|
|
148
|
+
# return request
|
|
149
|
+
#
|
|
150
|
+
# async def enqueue_request(self, request):
|
|
151
|
+
# if not request.dont_filter and await common_call(self.dupe_filter.requested, request):
|
|
152
|
+
# self.dupe_filter.log_stats(request)
|
|
153
|
+
# return False
|
|
154
|
+
# set_request(request, self.priority)
|
|
155
|
+
# await self.request_queue.put(request)
|
|
156
|
+
# return True
|
|
157
|
+
#
|
|
158
|
+
# def idle(self) -> bool:
|
|
159
|
+
# return len(self) == 0
|
|
160
|
+
#
|
|
161
|
+
# async def close(self):
|
|
162
|
+
# if isinstance(closed := getattr(self.dupe_filter, 'closed', None), Callable):
|
|
163
|
+
# await closed()
|
|
164
|
+
#
|
|
165
|
+
# def __len__(self):
|
|
166
|
+
# return self.request_queue.qsize()
|