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
crawlo/stats_collector.py
CHANGED
|
@@ -1,59 +1,59 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
"""
|
|
4
|
-
# @Time : 2025-05-17 09:57
|
|
5
|
-
# @Author : crawl-coder
|
|
6
|
-
# @Desc : 统计信息收集器
|
|
7
|
-
"""
|
|
8
|
-
from pprint import pformat
|
|
9
|
-
from crawlo.utils.log import get_logger
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
class StatsCollector(object):
|
|
13
|
-
|
|
14
|
-
def __init__(self, crawler):
|
|
15
|
-
self.crawler = crawler
|
|
16
|
-
self._dump = self.crawler.settings.get_bool('STATS_DUMP')
|
|
17
|
-
self._stats = {}
|
|
18
|
-
self.logger = get_logger(self.__class__.__name__, "INFO")
|
|
19
|
-
|
|
20
|
-
def inc_value(self, key, count=1, start=0):
|
|
21
|
-
self._stats[key] = self._stats.setdefault(key, start) + count
|
|
22
|
-
|
|
23
|
-
def get_value(self, key, default=None):
|
|
24
|
-
return self._stats.get(key, default)
|
|
25
|
-
|
|
26
|
-
def get_stats(self):
|
|
27
|
-
return self._stats
|
|
28
|
-
|
|
29
|
-
def set_stats(self, stats):
|
|
30
|
-
self._stats = stats
|
|
31
|
-
|
|
32
|
-
def clear_stats(self):
|
|
33
|
-
self._stats.clear()
|
|
34
|
-
|
|
35
|
-
def close_spider(self, spider, reason):
|
|
36
|
-
self._stats['reason'] = reason
|
|
37
|
-
|
|
38
|
-
# 首选:使用 spider.name
|
|
39
|
-
# 次选:使用实例的类名
|
|
40
|
-
# 最后:使用一个完全未知的占位符
|
|
41
|
-
spider_name = (
|
|
42
|
-
getattr(spider, 'name', None) or
|
|
43
|
-
spider.__class__.__name__ or
|
|
44
|
-
'<Unknown>'
|
|
45
|
-
)
|
|
46
|
-
|
|
47
|
-
self._stats['spider_name'] = spider_name
|
|
48
|
-
|
|
49
|
-
if self._dump:
|
|
50
|
-
self.logger.info(f'{spider_name} stats: \n{pformat(self._stats)}')
|
|
51
|
-
|
|
52
|
-
def __getitem__(self, item):
|
|
53
|
-
return self._stats[item]
|
|
54
|
-
|
|
55
|
-
def __setitem__(self, key, value):
|
|
56
|
-
self._stats[key] = value
|
|
57
|
-
|
|
58
|
-
def __delitem__(self, key):
|
|
59
|
-
del self._stats[key]
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
# @Time : 2025-05-17 09:57
|
|
5
|
+
# @Author : crawl-coder
|
|
6
|
+
# @Desc : 统计信息收集器
|
|
7
|
+
"""
|
|
8
|
+
from pprint import pformat
|
|
9
|
+
from crawlo.utils.log import get_logger
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class StatsCollector(object):
|
|
13
|
+
|
|
14
|
+
def __init__(self, crawler):
|
|
15
|
+
self.crawler = crawler
|
|
16
|
+
self._dump = self.crawler.settings.get_bool('STATS_DUMP')
|
|
17
|
+
self._stats = {}
|
|
18
|
+
self.logger = get_logger(self.__class__.__name__, "INFO")
|
|
19
|
+
|
|
20
|
+
def inc_value(self, key, count=1, start=0):
|
|
21
|
+
self._stats[key] = self._stats.setdefault(key, start) + count
|
|
22
|
+
|
|
23
|
+
def get_value(self, key, default=None):
|
|
24
|
+
return self._stats.get(key, default)
|
|
25
|
+
|
|
26
|
+
def get_stats(self):
|
|
27
|
+
return self._stats
|
|
28
|
+
|
|
29
|
+
def set_stats(self, stats):
|
|
30
|
+
self._stats = stats
|
|
31
|
+
|
|
32
|
+
def clear_stats(self):
|
|
33
|
+
self._stats.clear()
|
|
34
|
+
|
|
35
|
+
def close_spider(self, spider, reason):
|
|
36
|
+
self._stats['reason'] = reason
|
|
37
|
+
|
|
38
|
+
# 首选:使用 spider.name
|
|
39
|
+
# 次选:使用实例的类名
|
|
40
|
+
# 最后:使用一个完全未知的占位符
|
|
41
|
+
spider_name = (
|
|
42
|
+
getattr(spider, 'name', None) or
|
|
43
|
+
spider.__class__.__name__ or
|
|
44
|
+
'<Unknown>'
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
self._stats['spider_name'] = spider_name
|
|
48
|
+
|
|
49
|
+
if self._dump:
|
|
50
|
+
self.logger.info(f'{spider_name} stats: \n{pformat(self._stats)}')
|
|
51
|
+
|
|
52
|
+
def __getitem__(self, item):
|
|
53
|
+
return self._stats[item]
|
|
54
|
+
|
|
55
|
+
def __setitem__(self, key, value):
|
|
56
|
+
self._stats[key] = value
|
|
57
|
+
|
|
58
|
+
def __delitem__(self, key):
|
|
59
|
+
del self._stats[key]
|
crawlo/subscriber.py
CHANGED
|
@@ -1,106 +1,106 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
import asyncio
|
|
4
|
-
from collections import defaultdict
|
|
5
|
-
from inspect import iscoroutinefunction
|
|
6
|
-
from typing import Dict, Set, Callable, Coroutine, Any, TypeAlias, List
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class ReceiverTypeError(TypeError):
|
|
10
|
-
"""当订阅的接收者不是一个协程函数时抛出。"""
|
|
11
|
-
pass
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
ReceiverCoroutine: TypeAlias = Callable[..., Coroutine[Any, Any, Any]]
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class Subscriber:
|
|
18
|
-
"""
|
|
19
|
-
一个支持异步协程的发布/订阅(Pub/Sub)模式实现。
|
|
20
|
-
|
|
21
|
-
这个类允许你注册(订阅)协程函数来监听特定事件,并在事件发生时
|
|
22
|
-
以并发的方式异步地通知所有订阅者。
|
|
23
|
-
"""
|
|
24
|
-
|
|
25
|
-
def __init__(self):
|
|
26
|
-
"""初始化一个空的订阅者字典。"""
|
|
27
|
-
self._subscribers: Dict[str, Set[ReceiverCoroutine]] = defaultdict(set)
|
|
28
|
-
|
|
29
|
-
def subscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
30
|
-
"""
|
|
31
|
-
订阅一个事件。
|
|
32
|
-
|
|
33
|
-
Args:
|
|
34
|
-
receiver: 一个协程函数 (例如 async def my_func(...))。
|
|
35
|
-
event: 要订阅的事件名称。
|
|
36
|
-
|
|
37
|
-
Raises:
|
|
38
|
-
ReceiverTypeError: 如果提供的 `receiver` 不是一个协程函数。
|
|
39
|
-
"""
|
|
40
|
-
if not iscoroutinefunction(receiver):
|
|
41
|
-
raise ReceiverTypeError(f"接收者 '{receiver.__qualname__}' 必须是一个协程函数。")
|
|
42
|
-
self._subscribers[event].add(receiver)
|
|
43
|
-
|
|
44
|
-
def unsubscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
45
|
-
"""
|
|
46
|
-
取消订阅一个事件。
|
|
47
|
-
|
|
48
|
-
如果事件或接收者不存在,将静默处理。
|
|
49
|
-
|
|
50
|
-
Args:
|
|
51
|
-
receiver: 要取消订阅的协程函数。
|
|
52
|
-
event: 事件名称。
|
|
53
|
-
"""
|
|
54
|
-
if event in self._subscribers:
|
|
55
|
-
self._subscribers[event].discard(receiver)
|
|
56
|
-
|
|
57
|
-
async def notify(self, event: str, *args, **kwargs) -> List[Any]:
|
|
58
|
-
"""
|
|
59
|
-
异步地、并发地通知所有订阅了该事件的接收者。
|
|
60
|
-
|
|
61
|
-
此方法会等待所有订阅者任务完成后再返回,并收集所有结果或异常。
|
|
62
|
-
|
|
63
|
-
Args:
|
|
64
|
-
event: 要触发的事件名称。
|
|
65
|
-
*args: 传递给接收者的位置参数。
|
|
66
|
-
**kwargs: 传递给接收者的关键字参数。
|
|
67
|
-
|
|
68
|
-
Returns:
|
|
69
|
-
一个列表,包含每个订阅者任务的返回结果或在执行期间捕获的异常。
|
|
70
|
-
"""
|
|
71
|
-
receivers = self._subscribers.get(event, set())
|
|
72
|
-
if not receivers:
|
|
73
|
-
return []
|
|
74
|
-
|
|
75
|
-
tasks = [asyncio.create_task(receiver(*args, **kwargs)) for receiver in receivers]
|
|
76
|
-
|
|
77
|
-
# 并发执行所有任务并返回结果列表(包括异常)
|
|
78
|
-
return await asyncio.gather(*tasks, return_exceptions=True)
|
|
79
|
-
|
|
80
|
-
# #!/usr/bin/python
|
|
81
|
-
# # -*- coding:UTF-8 -*-
|
|
82
|
-
# import asyncio
|
|
83
|
-
# from collections import defaultdict
|
|
84
|
-
# from inspect import iscoroutinefunction
|
|
85
|
-
# from typing import Dict, Set, Callable, Coroutine
|
|
86
|
-
#
|
|
87
|
-
# from crawlo.exceptions import ReceiverTypeError
|
|
88
|
-
#
|
|
89
|
-
#
|
|
90
|
-
# class Subscriber:
|
|
91
|
-
#
|
|
92
|
-
# def __init__(self):
|
|
93
|
-
# self._subscribers: Dict[str, Set[Callable[..., Coroutine]]] = defaultdict(set)
|
|
94
|
-
#
|
|
95
|
-
# def subscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
96
|
-
# if not iscoroutinefunction(receiver):
|
|
97
|
-
# raise ReceiverTypeError(f"{receiver.__qualname__} must be a coroutine function")
|
|
98
|
-
# self._subscribers[event].add(receiver)
|
|
99
|
-
#
|
|
100
|
-
# def unsubscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
101
|
-
# self._subscribers[event].discard(receiver)
|
|
102
|
-
#
|
|
103
|
-
# async def notify(self, event: str, *args, **kwargs) -> None:
|
|
104
|
-
# for receiver in self._subscribers[event]:
|
|
105
|
-
# # 不能 await
|
|
106
|
-
# asyncio.create_task(receiver(*args, **kwargs))
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
import asyncio
|
|
4
|
+
from collections import defaultdict
|
|
5
|
+
from inspect import iscoroutinefunction
|
|
6
|
+
from typing import Dict, Set, Callable, Coroutine, Any, TypeAlias, List
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ReceiverTypeError(TypeError):
|
|
10
|
+
"""当订阅的接收者不是一个协程函数时抛出。"""
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
ReceiverCoroutine: TypeAlias = Callable[..., Coroutine[Any, Any, Any]]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Subscriber:
|
|
18
|
+
"""
|
|
19
|
+
一个支持异步协程的发布/订阅(Pub/Sub)模式实现。
|
|
20
|
+
|
|
21
|
+
这个类允许你注册(订阅)协程函数来监听特定事件,并在事件发生时
|
|
22
|
+
以并发的方式异步地通知所有订阅者。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self):
|
|
26
|
+
"""初始化一个空的订阅者字典。"""
|
|
27
|
+
self._subscribers: Dict[str, Set[ReceiverCoroutine]] = defaultdict(set)
|
|
28
|
+
|
|
29
|
+
def subscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
30
|
+
"""
|
|
31
|
+
订阅一个事件。
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
receiver: 一个协程函数 (例如 async def my_func(...))。
|
|
35
|
+
event: 要订阅的事件名称。
|
|
36
|
+
|
|
37
|
+
Raises:
|
|
38
|
+
ReceiverTypeError: 如果提供的 `receiver` 不是一个协程函数。
|
|
39
|
+
"""
|
|
40
|
+
if not iscoroutinefunction(receiver):
|
|
41
|
+
raise ReceiverTypeError(f"接收者 '{receiver.__qualname__}' 必须是一个协程函数。")
|
|
42
|
+
self._subscribers[event].add(receiver)
|
|
43
|
+
|
|
44
|
+
def unsubscribe(self, receiver: ReceiverCoroutine, *, event: str) -> None:
|
|
45
|
+
"""
|
|
46
|
+
取消订阅一个事件。
|
|
47
|
+
|
|
48
|
+
如果事件或接收者不存在,将静默处理。
|
|
49
|
+
|
|
50
|
+
Args:
|
|
51
|
+
receiver: 要取消订阅的协程函数。
|
|
52
|
+
event: 事件名称。
|
|
53
|
+
"""
|
|
54
|
+
if event in self._subscribers:
|
|
55
|
+
self._subscribers[event].discard(receiver)
|
|
56
|
+
|
|
57
|
+
async def notify(self, event: str, *args, **kwargs) -> List[Any]:
|
|
58
|
+
"""
|
|
59
|
+
异步地、并发地通知所有订阅了该事件的接收者。
|
|
60
|
+
|
|
61
|
+
此方法会等待所有订阅者任务完成后再返回,并收集所有结果或异常。
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
event: 要触发的事件名称。
|
|
65
|
+
*args: 传递给接收者的位置参数。
|
|
66
|
+
**kwargs: 传递给接收者的关键字参数。
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
一个列表,包含每个订阅者任务的返回结果或在执行期间捕获的异常。
|
|
70
|
+
"""
|
|
71
|
+
receivers = self._subscribers.get(event, set())
|
|
72
|
+
if not receivers:
|
|
73
|
+
return []
|
|
74
|
+
|
|
75
|
+
tasks = [asyncio.create_task(receiver(*args, **kwargs)) for receiver in receivers]
|
|
76
|
+
|
|
77
|
+
# 并发执行所有任务并返回结果列表(包括异常)
|
|
78
|
+
return await asyncio.gather(*tasks, return_exceptions=True)
|
|
79
|
+
|
|
80
|
+
# #!/usr/bin/python
|
|
81
|
+
# # -*- coding:UTF-8 -*-
|
|
82
|
+
# import asyncio
|
|
83
|
+
# from collections import defaultdict
|
|
84
|
+
# from inspect import iscoroutinefunction
|
|
85
|
+
# from typing import Dict, Set, Callable, Coroutine
|
|
86
|
+
#
|
|
87
|
+
# from crawlo.exceptions import ReceiverTypeError
|
|
88
|
+
#
|
|
89
|
+
#
|
|
90
|
+
# class Subscriber:
|
|
91
|
+
#
|
|
92
|
+
# def __init__(self):
|
|
93
|
+
# self._subscribers: Dict[str, Set[Callable[..., Coroutine]]] = defaultdict(set)
|
|
94
|
+
#
|
|
95
|
+
# def subscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
96
|
+
# if not iscoroutinefunction(receiver):
|
|
97
|
+
# raise ReceiverTypeError(f"{receiver.__qualname__} must be a coroutine function")
|
|
98
|
+
# self._subscribers[event].add(receiver)
|
|
99
|
+
#
|
|
100
|
+
# def unsubscribe(self, receiver: Callable[..., Coroutine], *, event: str) -> None:
|
|
101
|
+
# self._subscribers[event].discard(receiver)
|
|
102
|
+
#
|
|
103
|
+
# async def notify(self, event: str, *args, **kwargs) -> None:
|
|
104
|
+
# for receiver in self._subscribers[event]:
|
|
105
|
+
# # 不能 await
|
|
106
|
+
# asyncio.create_task(receiver(*args, **kwargs))
|
crawlo/task_manager.py
CHANGED
|
@@ -1,27 +1,30 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
import asyncio
|
|
4
|
-
from asyncio import Task, Future, Semaphore
|
|
5
|
-
from typing import Set, Final
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
class TaskManager:
|
|
9
|
-
|
|
10
|
-
def __init__(self, total_concurrency: int = 8):
|
|
11
|
-
self.current_task: Final[Set] = set()
|
|
12
|
-
self.semaphore: Semaphore = Semaphore(total_concurrency)
|
|
13
|
-
|
|
14
|
-
def create_task(self, coroutine) -> Task:
|
|
15
|
-
|
|
16
|
-
self.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
return
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
import asyncio
|
|
4
|
+
from asyncio import Task, Future, Semaphore
|
|
5
|
+
from typing import Set, Final
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TaskManager:
|
|
9
|
+
|
|
10
|
+
def __init__(self, total_concurrency: int = 8):
|
|
11
|
+
self.current_task: Final[Set] = set()
|
|
12
|
+
self.semaphore: Semaphore = Semaphore(total_concurrency)
|
|
13
|
+
|
|
14
|
+
async def create_task(self, coroutine) -> Task:
|
|
15
|
+
# 等待信号量,控制并发数
|
|
16
|
+
await self.semaphore.acquire()
|
|
17
|
+
|
|
18
|
+
task = asyncio.create_task(coroutine)
|
|
19
|
+
self.current_task.add(task)
|
|
20
|
+
|
|
21
|
+
def done_callback(_future: Future) -> None:
|
|
22
|
+
self.current_task.remove(task)
|
|
23
|
+
self.semaphore.release()
|
|
24
|
+
|
|
25
|
+
task.add_done_callback(done_callback)
|
|
26
|
+
|
|
27
|
+
return task
|
|
28
|
+
|
|
29
|
+
def all_done(self) -> bool:
|
|
30
|
+
return len(self.current_task) == 0
|
crawlo/templates/crawlo.cfg.tmpl
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
# crawlo.cfg
|
|
2
|
-
# 项目的配置文件。
|
|
3
|
-
|
|
4
|
-
[settings]
|
|
5
|
-
# 指定 settings 模块的导入路径
|
|
6
|
-
default = {{project_name}}.settings
|
|
7
|
-
|
|
8
|
-
[deploy]
|
|
9
|
-
# (可选)用于部署配置
|
|
10
|
-
# url = http://localhost:6800/
|
|
1
|
+
# crawlo.cfg
|
|
2
|
+
# 项目的配置文件。
|
|
3
|
+
|
|
4
|
+
[settings]
|
|
5
|
+
# 指定 settings 模块的导入路径
|
|
6
|
+
default = {{project_name}}.settings
|
|
7
|
+
|
|
8
|
+
[deploy]
|
|
9
|
+
# (可选)用于部署配置
|
|
10
|
+
# url = http://localhost:6800/
|
|
11
11
|
# project = {{project_name}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# -*- coding: UTF-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
{{project_name}} 项目包
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
{{project_name}} 项目包
|
|
4
4
|
"""
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
# -*- coding: UTF-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
{{project_name}}.items
|
|
4
|
-
======================
|
|
5
|
-
定义你抓取的数据结构。
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
from crawlo.items import Item, Field
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class ExampleItem(Item):
|
|
12
|
-
"""
|
|
13
|
-
一个示例数据项。
|
|
14
|
-
"""
|
|
15
|
-
# name = Field()
|
|
16
|
-
# price = Field()
|
|
17
|
-
# description = Field()
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
{{project_name}}.items
|
|
4
|
+
======================
|
|
5
|
+
定义你抓取的数据结构。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from crawlo.items import Item, Field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ExampleItem(Item):
|
|
12
|
+
"""
|
|
13
|
+
一个示例数据项。
|
|
14
|
+
"""
|
|
15
|
+
# name = Field()
|
|
16
|
+
# price = Field()
|
|
17
|
+
# description = Field()
|
|
18
18
|
pass
|
|
@@ -1,76 +1,87 @@
|
|
|
1
|
-
# -*- coding: UTF-8 -*-
|
|
2
|
-
"""
|
|
3
|
-
{{project_name}}.middlewares
|
|
4
|
-
============================
|
|
5
|
-
自定义中间件,用于在请求/响应/异常处理过程中插入自定义逻辑。
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
#
|
|
76
|
-
|
|
1
|
+
# -*- coding: UTF-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
{{project_name}}.middlewares
|
|
4
|
+
============================
|
|
5
|
+
自定义中间件,用于在请求/响应/异常处理过程中插入自定义逻辑。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import random
|
|
9
|
+
from crawlo import Request, Response
|
|
10
|
+
from crawlo.utils.log import get_logger
|
|
11
|
+
from crawlo.exceptions import IgnoreRequest
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RandomUserAgentMiddleware:
|
|
15
|
+
"""随机 User-Agent 中间件。"""
|
|
16
|
+
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
19
|
+
self.user_agents = [
|
|
20
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
|
|
21
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
|
|
22
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
23
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
def process_request(self, request, spider):
|
|
27
|
+
if 'User-Agent' not in request.headers:
|
|
28
|
+
ua = random.choice(self.user_agents)
|
|
29
|
+
request.headers['User-Agent'] = ua
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CustomDownloaderMiddleware:
|
|
34
|
+
"""自定义下载器中间件示例。"""
|
|
35
|
+
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
38
|
+
|
|
39
|
+
def process_request(self, request, spider):
|
|
40
|
+
"""在请求被下载器执行前调用。"""
|
|
41
|
+
# 示例:添加自定义请求头
|
|
42
|
+
# request.headers['Custom-Header'] = 'Custom-Value'
|
|
43
|
+
# 示例:设置代理
|
|
44
|
+
# request.meta['proxy'] = 'http://proxy.example.com:8080'
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
def process_response(self, request, response, spider):
|
|
48
|
+
"""在响应被 Spider 处理前调用。"""
|
|
49
|
+
# 示例:检查响应状态
|
|
50
|
+
if response.status_code == 403:
|
|
51
|
+
self.logger.warning(f"访问被拒绝: {request.url}")
|
|
52
|
+
return response
|
|
53
|
+
|
|
54
|
+
def process_exception(self, request, exception, spider):
|
|
55
|
+
"""在下载或处理过程中发生异常时调用。"""
|
|
56
|
+
self.logger.error(f"请求异常: {request.url} - {exception}")
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CustomSpiderMiddleware:
|
|
61
|
+
"""
|
|
62
|
+
Spider 中间件示例。
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
def __init__(self):
|
|
66
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
67
|
+
|
|
68
|
+
def process_spider_input(self, response, spider):
|
|
69
|
+
"""在 Spider 的 parse 方法被调用前调用。"""
|
|
70
|
+
# 可以用来验证响应
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
def process_spider_output(self, response, result, spider):
|
|
74
|
+
"""在 Spider 的 parse 方法返回结果后调用。"""
|
|
75
|
+
# 可以用来过滤或修改结果
|
|
76
|
+
for item in result:
|
|
77
|
+
yield item
|
|
78
|
+
|
|
79
|
+
def process_spider_exception(self, response, exception, spider):
|
|
80
|
+
"""在 Spider 的 parse 方法抛出异常时调用。"""
|
|
81
|
+
self.logger.error(f"Spider 异常: {response.url} - {exception}")
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
def process_start_requests(self, start_requests, spider):
|
|
85
|
+
"""在 Spider 的 start_requests 生成器被消费时调用。"""
|
|
86
|
+
for request in start_requests:
|
|
87
|
+
yield request
|