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/exceptions.py
CHANGED
|
@@ -1,78 +1,78 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
class TransformTypeError(TypeError):
|
|
4
|
-
pass
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
class OutputError(Exception):
|
|
8
|
-
pass
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class SpiderTypeError(TypeError):
|
|
12
|
-
pass
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
class ItemInitError(Exception):
|
|
16
|
-
pass
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class ItemAttributeError(Exception):
|
|
20
|
-
pass
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
class DecodeError(Exception):
|
|
24
|
-
pass
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
class MiddlewareInitError(Exception):
|
|
28
|
-
pass
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
class PipelineInitError(Exception):
|
|
32
|
-
pass
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
class InvalidOutputError(Exception):
|
|
36
|
-
pass
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
class RequestMethodError(Exception):
|
|
40
|
-
pass
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
class IgnoreRequestError(Exception):
|
|
44
|
-
def __init__(self, msg):
|
|
45
|
-
self.msg = msg
|
|
46
|
-
super(IgnoreRequestError, self).__init__(msg)
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
class ItemDiscard(Exception):
|
|
50
|
-
def __init__(self, msg):
|
|
51
|
-
self.msg = msg
|
|
52
|
-
super(ItemDiscard, self).__init__(msg)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
class NotConfigured(Exception):
|
|
56
|
-
pass
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
class NotConfiguredError(Exception):
|
|
60
|
-
pass
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
class ExtensionInitError(Exception):
|
|
64
|
-
pass
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
class ReceiverTypeError(Exception):
|
|
68
|
-
pass
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
class SpiderCreationError(Exception):
|
|
72
|
-
"""爬虫实例化失败异常"""
|
|
73
|
-
pass
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
class ItemValidationError(Exception):
|
|
77
|
-
"""Item 字段验证错误"""
|
|
78
|
-
pass
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
class TransformTypeError(TypeError):
|
|
4
|
+
pass
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OutputError(Exception):
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SpiderTypeError(TypeError):
|
|
12
|
+
pass
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ItemInitError(Exception):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ItemAttributeError(Exception):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class DecodeError(Exception):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MiddlewareInitError(Exception):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PipelineInitError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class InvalidOutputError(Exception):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class RequestMethodError(Exception):
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class IgnoreRequestError(Exception):
|
|
44
|
+
def __init__(self, msg):
|
|
45
|
+
self.msg = msg
|
|
46
|
+
super(IgnoreRequestError, self).__init__(msg)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class ItemDiscard(Exception):
|
|
50
|
+
def __init__(self, msg):
|
|
51
|
+
self.msg = msg
|
|
52
|
+
super(ItemDiscard, self).__init__(msg)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class NotConfigured(Exception):
|
|
56
|
+
pass
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class NotConfiguredError(Exception):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ExtensionInitError(Exception):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class ReceiverTypeError(Exception):
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class SpiderCreationError(Exception):
|
|
72
|
+
"""爬虫实例化失败异常"""
|
|
73
|
+
pass
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ItemValidationError(Exception):
|
|
77
|
+
"""Item 字段验证错误"""
|
|
78
|
+
pass
|
crawlo/extension/__init__.py
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
from typing import List
|
|
4
|
-
from pprint import pformat
|
|
5
|
-
|
|
6
|
-
from crawlo.utils.log import get_logger
|
|
7
|
-
from crawlo.
|
|
8
|
-
from crawlo.exceptions import ExtensionInitError
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class ExtensionManager(object):
|
|
12
|
-
|
|
13
|
-
def __init__(self, crawler):
|
|
14
|
-
self.crawler = crawler
|
|
15
|
-
self.extensions: List = []
|
|
16
|
-
extensions = self.crawler.settings.get_list('EXTENSIONS')
|
|
17
|
-
self.logger = get_logger(self.__class__.__name__, crawler.settings.get('LOG_LEVEL'))
|
|
18
|
-
self._add_extensions(extensions)
|
|
19
|
-
|
|
20
|
-
@classmethod
|
|
21
|
-
def create_instance(cls, *args, **kwargs):
|
|
22
|
-
return cls(*args, **kwargs)
|
|
23
|
-
|
|
24
|
-
def _add_extensions(self, extensions):
|
|
25
|
-
for extension in extensions:
|
|
26
|
-
extension_cls = load_class(extension)
|
|
27
|
-
if not hasattr(extension_cls, 'create_instance'):
|
|
28
|
-
raise ExtensionInitError(f"extension init failed, Must have method 'create_instance()")
|
|
29
|
-
self.extensions.append(extension_cls.create_instance(self.crawler))
|
|
30
|
-
if extensions:
|
|
31
|
-
self.logger.info(f"enabled extensions: \n {pformat(extensions)}")
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
from typing import List
|
|
4
|
+
from pprint import pformat
|
|
5
|
+
|
|
6
|
+
from crawlo.utils.log import get_logger
|
|
7
|
+
from crawlo.project import load_class
|
|
8
|
+
from crawlo.exceptions import ExtensionInitError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ExtensionManager(object):
|
|
12
|
+
|
|
13
|
+
def __init__(self, crawler):
|
|
14
|
+
self.crawler = crawler
|
|
15
|
+
self.extensions: List = []
|
|
16
|
+
extensions = self.crawler.settings.get_list('EXTENSIONS')
|
|
17
|
+
self.logger = get_logger(self.__class__.__name__, crawler.settings.get('LOG_LEVEL'))
|
|
18
|
+
self._add_extensions(extensions)
|
|
19
|
+
|
|
20
|
+
@classmethod
|
|
21
|
+
def create_instance(cls, *args, **kwargs):
|
|
22
|
+
return cls(*args, **kwargs)
|
|
23
|
+
|
|
24
|
+
def _add_extensions(self, extensions):
|
|
25
|
+
for extension in extensions:
|
|
26
|
+
extension_cls = load_class(extension)
|
|
27
|
+
if not hasattr(extension_cls, 'create_instance'):
|
|
28
|
+
raise ExtensionInitError(f"extension init failed, Must have method 'create_instance()")
|
|
29
|
+
self.extensions.append(extension_cls.create_instance(self.crawler))
|
|
30
|
+
if extensions:
|
|
31
|
+
self.logger.info(f"enabled extensions: \n {pformat(extensions)}")
|
crawlo/extension/log_interval.py
CHANGED
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
import asyncio
|
|
4
|
-
|
|
5
|
-
from crawlo.utils.log import get_logger
|
|
6
|
-
from crawlo.event import spider_opened, spider_closed
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
class LogIntervalExtension(object):
|
|
10
|
-
|
|
11
|
-
def __init__(self, crawler):
|
|
12
|
-
self.task = None
|
|
13
|
-
self.stats = crawler.stats
|
|
14
|
-
self.item_count = 0
|
|
15
|
-
self.response_count = 0
|
|
16
|
-
self.seconds = crawler.settings.get('INTERVAL')
|
|
17
|
-
self.interval = int(self.seconds / 60) if self.seconds % 60 == 0 else self.seconds
|
|
18
|
-
self.interval = "" if self.interval == 1 else self.interval
|
|
19
|
-
self.unit = 'min' if self.seconds % 60 == 0 else 's'
|
|
20
|
-
|
|
21
|
-
self.logger = get_logger(self.__class__.__name__, crawler.settings.get('LOG_LEVEL'))
|
|
22
|
-
|
|
23
|
-
@classmethod
|
|
24
|
-
def create_instance(cls, crawler):
|
|
25
|
-
o = cls(crawler)
|
|
26
|
-
crawler.subscriber.subscribe(o.spider_opened, event=spider_opened)
|
|
27
|
-
crawler.subscriber.subscribe(o.spider_closed, event=spider_closed)
|
|
28
|
-
return o
|
|
29
|
-
|
|
30
|
-
async def spider_opened(self):
|
|
31
|
-
self.task = asyncio.create_task(self.interval_log())
|
|
32
|
-
await self.task
|
|
33
|
-
|
|
34
|
-
async def spider_closed(self):
|
|
35
|
-
if self.task:
|
|
36
|
-
self.task.cancel()
|
|
37
|
-
|
|
38
|
-
async def interval_log(self):
|
|
39
|
-
while True:
|
|
40
|
-
last_item_count = self.stats.get_value('item_successful_count', default=0)
|
|
41
|
-
last_response_count = self.stats.get_value('response_received_count', default=0)
|
|
42
|
-
item_rate = last_item_count - self.item_count
|
|
43
|
-
response_rate = last_response_count - self.response_count
|
|
44
|
-
self.item_count, self.response_count = last_item_count, last_response_count
|
|
45
|
-
self.logger.info(
|
|
46
|
-
f'Crawled {last_response_count} pages (at {response_rate} pages/{self.interval}{self.unit}),'
|
|
47
|
-
f' Got {last_item_count} items (at {item_rate} items/{self.interval}{self.unit}).'
|
|
48
|
-
)
|
|
49
|
-
await asyncio.sleep(self.seconds)
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
import asyncio
|
|
4
|
+
|
|
5
|
+
from crawlo.utils.log import get_logger
|
|
6
|
+
from crawlo.event import spider_opened, spider_closed
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LogIntervalExtension(object):
|
|
10
|
+
|
|
11
|
+
def __init__(self, crawler):
|
|
12
|
+
self.task = None
|
|
13
|
+
self.stats = crawler.stats
|
|
14
|
+
self.item_count = 0
|
|
15
|
+
self.response_count = 0
|
|
16
|
+
self.seconds = crawler.settings.get('INTERVAL')
|
|
17
|
+
self.interval = int(self.seconds / 60) if self.seconds % 60 == 0 else self.seconds
|
|
18
|
+
self.interval = "" if self.interval == 1 else self.interval
|
|
19
|
+
self.unit = 'min' if self.seconds % 60 == 0 else 's'
|
|
20
|
+
|
|
21
|
+
self.logger = get_logger(self.__class__.__name__, crawler.settings.get('LOG_LEVEL'))
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def create_instance(cls, crawler):
|
|
25
|
+
o = cls(crawler)
|
|
26
|
+
crawler.subscriber.subscribe(o.spider_opened, event=spider_opened)
|
|
27
|
+
crawler.subscriber.subscribe(o.spider_closed, event=spider_closed)
|
|
28
|
+
return o
|
|
29
|
+
|
|
30
|
+
async def spider_opened(self):
|
|
31
|
+
self.task = asyncio.create_task(self.interval_log())
|
|
32
|
+
await self.task
|
|
33
|
+
|
|
34
|
+
async def spider_closed(self):
|
|
35
|
+
if self.task:
|
|
36
|
+
self.task.cancel()
|
|
37
|
+
|
|
38
|
+
async def interval_log(self):
|
|
39
|
+
while True:
|
|
40
|
+
last_item_count = self.stats.get_value('item_successful_count', default=0)
|
|
41
|
+
last_response_count = self.stats.get_value('response_received_count', default=0)
|
|
42
|
+
item_rate = last_item_count - self.item_count
|
|
43
|
+
response_rate = last_response_count - self.response_count
|
|
44
|
+
self.item_count, self.response_count = last_item_count, last_response_count
|
|
45
|
+
self.logger.info(
|
|
46
|
+
f'Crawled {last_response_count} pages (at {response_rate} pages/{self.interval}{self.unit}),'
|
|
47
|
+
f' Got {last_item_count} items (at {item_rate} items/{self.interval}{self.unit}).'
|
|
48
|
+
)
|
|
49
|
+
await asyncio.sleep(self.seconds)
|
crawlo/extension/log_stats.py
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
from crawlo import event
|
|
4
|
-
from crawlo.utils.date_tools import now, time_diff
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
class LogStats(object):
|
|
8
|
-
|
|
9
|
-
def __init__(self, stats):
|
|
10
|
-
self._stats = stats
|
|
11
|
-
|
|
12
|
-
@classmethod
|
|
13
|
-
def create_instance(cls, crawler):
|
|
14
|
-
o = cls(crawler.stats)
|
|
15
|
-
crawler.subscriber.subscribe(o.spider_opened, event=event.spider_opened)
|
|
16
|
-
crawler.subscriber.subscribe(o.spider_closed, event=event.spider_closed)
|
|
17
|
-
crawler.subscriber.subscribe(o.item_successful, event=event.item_successful)
|
|
18
|
-
crawler.subscriber.subscribe(o.item_discard, event=event.item_discard)
|
|
19
|
-
crawler.subscriber.subscribe(o.response_received, event=event.response_received)
|
|
20
|
-
crawler.subscriber.subscribe(o.request_scheduled, event=event.request_scheduled)
|
|
21
|
-
|
|
22
|
-
return o
|
|
23
|
-
|
|
24
|
-
async def spider_opened(self):
|
|
25
|
-
self._stats['start_time'] = now(fmt='%Y-%m-%d %H:%M:%S')
|
|
26
|
-
|
|
27
|
-
async def spider_closed(self):
|
|
28
|
-
self._stats['end_time'] = now(fmt='%Y-%m-%d %H:%M:%S')
|
|
29
|
-
self._stats['cost_time(s)'] = time_diff(start=self._stats['start_time'], end=self._stats['end_time'])
|
|
30
|
-
|
|
31
|
-
async def item_successful(self, _item, _spider):
|
|
32
|
-
self._stats.inc_value('item_successful_count')
|
|
33
|
-
|
|
34
|
-
async def item_discard(self, _item, exc, _spider):
|
|
35
|
-
self._stats.inc_value('item_discard_count')
|
|
36
|
-
reason = exc.msg
|
|
37
|
-
if reason:
|
|
38
|
-
self._stats.inc_value(f"item_discard/{reason}")
|
|
39
|
-
|
|
40
|
-
async def response_received(self, _response, _spider):
|
|
41
|
-
self._stats.inc_value('response_received_count')
|
|
42
|
-
|
|
43
|
-
async def request_scheduled(self, _request, _spider):
|
|
44
|
-
self._stats.inc_value('request_scheduler_count')
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
from crawlo import event
|
|
4
|
+
from crawlo.utils.date_tools import now, time_diff
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class LogStats(object):
|
|
8
|
+
|
|
9
|
+
def __init__(self, stats):
|
|
10
|
+
self._stats = stats
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
def create_instance(cls, crawler):
|
|
14
|
+
o = cls(crawler.stats)
|
|
15
|
+
crawler.subscriber.subscribe(o.spider_opened, event=event.spider_opened)
|
|
16
|
+
crawler.subscriber.subscribe(o.spider_closed, event=event.spider_closed)
|
|
17
|
+
crawler.subscriber.subscribe(o.item_successful, event=event.item_successful)
|
|
18
|
+
crawler.subscriber.subscribe(o.item_discard, event=event.item_discard)
|
|
19
|
+
crawler.subscriber.subscribe(o.response_received, event=event.response_received)
|
|
20
|
+
crawler.subscriber.subscribe(o.request_scheduled, event=event.request_scheduled)
|
|
21
|
+
|
|
22
|
+
return o
|
|
23
|
+
|
|
24
|
+
async def spider_opened(self):
|
|
25
|
+
self._stats['start_time'] = now(fmt='%Y-%m-%d %H:%M:%S')
|
|
26
|
+
|
|
27
|
+
async def spider_closed(self):
|
|
28
|
+
self._stats['end_time'] = now(fmt='%Y-%m-%d %H:%M:%S')
|
|
29
|
+
self._stats['cost_time(s)'] = time_diff(start=self._stats['start_time'], end=self._stats['end_time'])
|
|
30
|
+
|
|
31
|
+
async def item_successful(self, _item, _spider):
|
|
32
|
+
self._stats.inc_value('item_successful_count')
|
|
33
|
+
|
|
34
|
+
async def item_discard(self, _item, exc, _spider):
|
|
35
|
+
self._stats.inc_value('item_discard_count')
|
|
36
|
+
reason = exc.msg
|
|
37
|
+
if reason:
|
|
38
|
+
self._stats.inc_value(f"item_discard/{reason}")
|
|
39
|
+
|
|
40
|
+
async def response_received(self, _response, _spider):
|
|
41
|
+
self._stats.inc_value('response_received_count')
|
|
42
|
+
|
|
43
|
+
async def request_scheduled(self, _request, _spider):
|
|
44
|
+
self._stats.inc_value('request_scheduler_count')
|
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
from crawlo.exceptions import NotConfigured
|
|
2
|
-
from crawlo.utils.log import get_logger
|
|
3
|
-
from crawlo.utils.log import LoggerManager
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
class CustomLoggerExtension:
|
|
7
|
-
"""
|
|
8
|
-
日志系统初始化扩展
|
|
9
|
-
遵循与 ExtensionManager 一致的接口规范:使用 create_instance
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
def __init__(self, settings):
|
|
13
|
-
self.settings = settings
|
|
14
|
-
# 初始化全局日志配置
|
|
15
|
-
LoggerManager.configure(settings)
|
|
16
|
-
|
|
17
|
-
@classmethod
|
|
18
|
-
def create_instance(cls, crawler, *args, **kwargs):
|
|
19
|
-
"""
|
|
20
|
-
工厂方法:兼容 ExtensionManager 的创建方式
|
|
21
|
-
被 ExtensionManager 调用
|
|
22
|
-
"""
|
|
23
|
-
# 可以通过 settings 控制是否启用
|
|
24
|
-
if not crawler.settings.get('LOG_FILE') and not crawler.settings.get('LOG_ENABLE_CUSTOM'):
|
|
25
|
-
raise NotConfigured("CustomLoggerExtension: LOG_FILE not set and LOG_ENABLE_CUSTOM=False")
|
|
26
|
-
|
|
27
|
-
return cls(crawler.settings)
|
|
28
|
-
|
|
29
|
-
def spider_opened(self, spider):
|
|
30
|
-
logger = get_logger(__name__)
|
|
31
|
-
logger.info(
|
|
32
|
-
f"CustomLoggerExtension: Logging initialized. "
|
|
33
|
-
f"LOG_FILE={self.settings.get('LOG_FILE')}, "
|
|
34
|
-
f"LOG_LEVEL={self.settings.get('LOG_LEVEL')}"
|
|
1
|
+
from crawlo.exceptions import NotConfigured
|
|
2
|
+
from crawlo.utils.log import get_logger
|
|
3
|
+
from crawlo.utils.log import LoggerManager
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CustomLoggerExtension:
|
|
7
|
+
"""
|
|
8
|
+
日志系统初始化扩展
|
|
9
|
+
遵循与 ExtensionManager 一致的接口规范:使用 create_instance
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, settings):
|
|
13
|
+
self.settings = settings
|
|
14
|
+
# 初始化全局日志配置
|
|
15
|
+
LoggerManager.configure(settings)
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def create_instance(cls, crawler, *args, **kwargs):
|
|
19
|
+
"""
|
|
20
|
+
工厂方法:兼容 ExtensionManager 的创建方式
|
|
21
|
+
被 ExtensionManager 调用
|
|
22
|
+
"""
|
|
23
|
+
# 可以通过 settings 控制是否启用
|
|
24
|
+
if not crawler.settings.get('LOG_FILE') and not crawler.settings.get('LOG_ENABLE_CUSTOM'):
|
|
25
|
+
raise NotConfigured("CustomLoggerExtension: LOG_FILE not set and LOG_ENABLE_CUSTOM=False")
|
|
26
|
+
|
|
27
|
+
return cls(crawler.settings)
|
|
28
|
+
|
|
29
|
+
def spider_opened(self, spider):
|
|
30
|
+
logger = get_logger(__name__)
|
|
31
|
+
logger.info(
|
|
32
|
+
f"CustomLoggerExtension: Logging initialized. "
|
|
33
|
+
f"LOG_FILE={self.settings.get('LOG_FILE')}, "
|
|
34
|
+
f"LOG_LEVEL={self.settings.get('LOG_LEVEL')}"
|
|
35
35
|
)
|
crawlo/filters/__init__.py
CHANGED
|
@@ -1,37 +1,154 @@
|
|
|
1
|
-
#!/usr/bin/python
|
|
2
|
-
# -*- coding:UTF-8 -*-
|
|
3
|
-
|
|
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
|
-
def
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding:UTF-8 -*-
|
|
3
|
+
"""
|
|
4
|
+
Crawlo Filters Module
|
|
5
|
+
====================
|
|
6
|
+
提供多种请求去重过滤器实现。
|
|
7
|
+
|
|
8
|
+
过滤器类型:
|
|
9
|
+
- MemoryFilter: 基于内存的高效去重,适合单机模式
|
|
10
|
+
- AioRedisFilter: 基于Redis的分布式去重,适合分布式模式
|
|
11
|
+
- MemoryFileFilter: 内存+文件持久化,适合需要重启恢复的场景
|
|
12
|
+
|
|
13
|
+
核心接口:
|
|
14
|
+
- BaseFilter: 所有过滤器的基类
|
|
15
|
+
- requested(): 检查请求是否重复的主要方法
|
|
16
|
+
"""
|
|
17
|
+
from abc import ABC, abstractmethod
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
from crawlo.utils.request import request_fingerprint
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BaseFilter(ABC):
|
|
24
|
+
"""
|
|
25
|
+
请求去重过滤器基类
|
|
26
|
+
|
|
27
|
+
提供统一的去重接口和统计功能。
|
|
28
|
+
所有过滤器实现都应该继承此类。
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
def __init__(self, logger, stats, debug: bool = False):
|
|
32
|
+
"""
|
|
33
|
+
初始化过滤器
|
|
34
|
+
|
|
35
|
+
:param logger: 日志器实例
|
|
36
|
+
:param stats: 统计信息存储
|
|
37
|
+
:param debug: 是否启用调试日志
|
|
38
|
+
"""
|
|
39
|
+
self.logger = logger
|
|
40
|
+
self.stats = stats
|
|
41
|
+
self.debug = debug
|
|
42
|
+
self._request_count = 0
|
|
43
|
+
self._duplicate_count = 0
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def create_instance(cls, *args, **kwargs) -> 'BaseFilter':
|
|
47
|
+
return cls(*args, **kwargs)
|
|
48
|
+
|
|
49
|
+
def requested(self, request) -> bool:
|
|
50
|
+
"""
|
|
51
|
+
检查请求是否重复(主要接口)
|
|
52
|
+
|
|
53
|
+
:param request: 请求对象
|
|
54
|
+
:return: True 表示重复,False 表示新请求
|
|
55
|
+
"""
|
|
56
|
+
self._request_count += 1
|
|
57
|
+
fp = request_fingerprint(request)
|
|
58
|
+
|
|
59
|
+
if fp in self:
|
|
60
|
+
self._duplicate_count += 1
|
|
61
|
+
self.log_stats(request)
|
|
62
|
+
return True
|
|
63
|
+
|
|
64
|
+
self.add_fingerprint(fp)
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
@abstractmethod
|
|
68
|
+
def add_fingerprint(self, fp: str) -> None:
|
|
69
|
+
"""
|
|
70
|
+
添加请求指纹(子类必须实现)
|
|
71
|
+
|
|
72
|
+
:param fp: 请求指纹字符串
|
|
73
|
+
"""
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
@abstractmethod
|
|
77
|
+
def __contains__(self, item: str) -> bool:
|
|
78
|
+
"""
|
|
79
|
+
检查指纹是否存在(支持 in 操作符)
|
|
80
|
+
|
|
81
|
+
:param item: 要检查的指纹
|
|
82
|
+
:return: 是否已存在
|
|
83
|
+
"""
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
def log_stats(self, request) -> None:
|
|
87
|
+
"""
|
|
88
|
+
记录统计信息
|
|
89
|
+
|
|
90
|
+
:param request: 重复的请求对象
|
|
91
|
+
"""
|
|
92
|
+
if self.debug:
|
|
93
|
+
self.logger.debug(f'Filtered duplicate request: {request}')
|
|
94
|
+
self.stats.inc_value(f'{self}/filtered_count')
|
|
95
|
+
|
|
96
|
+
def get_stats(self) -> dict:
|
|
97
|
+
"""
|
|
98
|
+
获取过滤器统计信息
|
|
99
|
+
|
|
100
|
+
:return: 统计信息字典
|
|
101
|
+
"""
|
|
102
|
+
return {
|
|
103
|
+
'total_requests': self._request_count,
|
|
104
|
+
'duplicate_requests': self._duplicate_count,
|
|
105
|
+
'unique_requests': self._request_count - self._duplicate_count,
|
|
106
|
+
'duplicate_rate': f"{self._duplicate_count / max(1, self._request_count) * 100:.2f}%"
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
def reset_stats(self) -> None:
|
|
110
|
+
"""重置统计信息"""
|
|
111
|
+
self._request_count = 0
|
|
112
|
+
self._duplicate_count = 0
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
"""关闭过滤器并清理资源"""
|
|
116
|
+
pass
|
|
117
|
+
|
|
118
|
+
def __str__(self) -> str:
|
|
119
|
+
return f'{self.__class__.__name__}'
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# 导出所有可用的过滤器
|
|
123
|
+
__all__ = ['BaseFilter']
|
|
124
|
+
|
|
125
|
+
# 动态导入具体实现
|
|
126
|
+
try:
|
|
127
|
+
from .memory_filter import MemoryFilter, MemoryFileFilter
|
|
128
|
+
__all__.extend(['MemoryFilter', 'MemoryFileFilter'])
|
|
129
|
+
except ImportError:
|
|
130
|
+
MemoryFilter = None
|
|
131
|
+
MemoryFileFilter = None
|
|
132
|
+
|
|
133
|
+
try:
|
|
134
|
+
from .aioredis_filter import AioRedisFilter
|
|
135
|
+
__all__.append('AioRedisFilter')
|
|
136
|
+
except ImportError:
|
|
137
|
+
AioRedisFilter = None
|
|
138
|
+
|
|
139
|
+
# 提供便捷的过滤器映射
|
|
140
|
+
FILTER_MAP = {
|
|
141
|
+
'memory': MemoryFilter,
|
|
142
|
+
'memory_file': MemoryFileFilter,
|
|
143
|
+
'redis': AioRedisFilter,
|
|
144
|
+
'aioredis': AioRedisFilter, # 别名
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
# 过滤掉不可用的过滤器
|
|
148
|
+
FILTER_MAP = {k: v for k, v in FILTER_MAP.items() if v is not None}
|
|
149
|
+
|
|
150
|
+
def get_filter_class(name: str):
|
|
151
|
+
"""根据名称获取过滤器类"""
|
|
152
|
+
if name in FILTER_MAP:
|
|
153
|
+
return FILTER_MAP[name]
|
|
154
|
+
raise ValueError(f"未知的过滤器类型: {name}。可用类型: {list(FILTER_MAP.keys())}")
|