crawlo 1.0.1__tar.gz → 1.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crawlo might be problematic. Click here for more details.

Files changed (100) hide show
  1. {crawlo-1.0.1 → crawlo-1.0.3}/LICENSE +22 -22
  2. crawlo-1.0.3/MANIFEST.in +17 -0
  3. {crawlo-1.0.1/crawlo.egg-info → crawlo-1.0.3}/PKG-INFO +48 -36
  4. crawlo-1.0.3/README.md +2 -0
  5. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/__init__.py +9 -6
  6. crawlo-1.0.3/crawlo/__version__.py +1 -0
  7. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/core/__init__.py +2 -2
  8. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/core/engine.py +158 -158
  9. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/core/processor.py +40 -40
  10. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/core/scheduler.py +57 -59
  11. crawlo-1.0.3/crawlo/crawler.py +242 -0
  12. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/downloader/__init__.py +78 -78
  13. crawlo-1.0.3/crawlo/downloader/aiohttp_downloader.py +259 -0
  14. crawlo-1.0.3/crawlo/downloader/httpx_downloader.py +187 -0
  15. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/downloader/playwright_downloader.py +160 -160
  16. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/event.py +11 -11
  17. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/exceptions.py +64 -64
  18. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/extension/__init__.py +31 -31
  19. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/extension/log_interval.py +49 -49
  20. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/extension/log_stats.py +44 -44
  21. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/filters/__init__.py +37 -37
  22. crawlo-1.0.3/crawlo/filters/aioredis_filter.py +158 -0
  23. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/filters/memory_filter.py +202 -203
  24. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/filters/redis_filter.py +119 -119
  25. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/items/__init__.py +62 -62
  26. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/items/items.py +118 -118
  27. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/__init__.py +21 -21
  28. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/default_header.py +32 -32
  29. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/download_delay.py +28 -28
  30. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/middleware_manager.py +140 -140
  31. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/request_ignore.py +30 -30
  32. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/response_code.py +18 -18
  33. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/response_filter.py +26 -26
  34. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/middleware/retry.py +90 -89
  35. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/network/__init__.py +7 -7
  36. crawlo-1.0.3/crawlo/network/request.py +205 -0
  37. crawlo-1.0.3/crawlo/network/response.py +166 -0
  38. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/__init__.py +13 -13
  39. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/console_pipeline.py +39 -39
  40. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/mongo_pipeline.py +116 -116
  41. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/mysql_batch_pipline.py +133 -133
  42. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/mysql_pipeline.py +195 -176
  43. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/pipelines/pipeline_manager.py +56 -56
  44. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/settings/__init__.py +7 -7
  45. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/settings/default_settings.py +93 -89
  46. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/settings/setting_manager.py +99 -99
  47. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/spider/__init__.py +36 -36
  48. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/stats_collector.py +59 -47
  49. crawlo-1.0.3/crawlo/subscriber.py +106 -0
  50. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/task_manager.py +27 -27
  51. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/item_template.tmpl +21 -21
  52. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/project_template/main.py +32 -32
  53. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/project_template/setting.py +189 -189
  54. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/spider_template.tmpl +30 -30
  55. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/__init__.py +7 -7
  56. crawlo-1.0.3/crawlo/utils/concurrency_manager.py +125 -0
  57. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/date_tools.py +177 -177
  58. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/func_tools.py +82 -82
  59. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/log.py +39 -39
  60. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/pqueue.py +173 -173
  61. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/project.py +59 -59
  62. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/request.py +122 -85
  63. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/system.py +11 -11
  64. crawlo-1.0.3/crawlo/utils/tools.py +303 -0
  65. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/utils/url.py +39 -39
  66. {crawlo-1.0.1 → crawlo-1.0.3/crawlo.egg-info}/PKG-INFO +48 -36
  67. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo.egg-info/SOURCES.txt +16 -1
  68. crawlo-1.0.3/crawlo.egg-info/requires.txt +34 -0
  69. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo.egg-info/top_level.txt +1 -0
  70. crawlo-1.0.3/pyproject.toml +3 -0
  71. crawlo-1.0.3/requirements.txt +21 -0
  72. {crawlo-1.0.1 → crawlo-1.0.3}/setup.cfg +67 -52
  73. crawlo-1.0.3/tests/__init__.py +7 -0
  74. crawlo-1.0.3/tests/baidu_spider/__init__.py +7 -0
  75. crawlo-1.0.3/tests/baidu_spider/demo.py +94 -0
  76. crawlo-1.0.3/tests/baidu_spider/items.py +25 -0
  77. crawlo-1.0.3/tests/baidu_spider/middleware.py +49 -0
  78. crawlo-1.0.3/tests/baidu_spider/pipeline.py +55 -0
  79. crawlo-1.0.3/tests/baidu_spider/request_fingerprints.txt +9 -0
  80. crawlo-1.0.3/tests/baidu_spider/run.py +27 -0
  81. crawlo-1.0.3/tests/baidu_spider/settings.py +78 -0
  82. crawlo-1.0.3/tests/baidu_spider/spiders/__init__.py +7 -0
  83. crawlo-1.0.3/tests/baidu_spider/spiders/bai_du.py +61 -0
  84. crawlo-1.0.3/tests/baidu_spider/spiders/sina.py +79 -0
  85. crawlo-1.0.1/MANIFEST.in +0 -11
  86. crawlo-1.0.1/README.md +0 -2
  87. crawlo-1.0.1/crawlo/__version__.py +0 -2
  88. crawlo-1.0.1/crawlo/crawler.py +0 -107
  89. crawlo-1.0.1/crawlo/downloader/aiohttp_downloader.py +0 -96
  90. crawlo-1.0.1/crawlo/downloader/httpx_downloader.py +0 -48
  91. crawlo-1.0.1/crawlo/filters/aioredis_filter.py +0 -130
  92. crawlo-1.0.1/crawlo/network/request.py +0 -155
  93. crawlo-1.0.1/crawlo/network/response.py +0 -93
  94. crawlo-1.0.1/crawlo/subscriber.py +0 -27
  95. crawlo-1.0.1/crawlo.egg-info/requires.txt +0 -20
  96. crawlo-1.0.1/pyproject.toml +0 -6
  97. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/project_template/items/__init__.py +0 -0
  98. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo/templates/project_template/spiders/__init__.py +0 -0
  99. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo.egg-info/dependency_links.txt +0 -0
  100. {crawlo-1.0.1 → crawlo-1.0.3}/crawlo.egg-info/entry_points.txt +0 -0
@@ -1,23 +1,23 @@
1
- MIT License
2
-
3
- Modifications:
4
-
5
- Copyright (c) 2020 crawl-coder <2251018029@qq.com>
6
-
7
- Permission is hereby granted, free of charge, to any person obtaining a copy
8
- of this software and associated documentation files (the "Software"), to deal
9
- in the Software without restriction, including without limitation the rights
10
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
- copies of the Software, and to permit persons to whom the Software is
12
- furnished to do so, subject to the following conditions:
13
-
14
- The above copyright notice and this permission notice shall be included in all
15
- copies or substantial portions of the Software.
16
-
17
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Modifications:
4
+
5
+ Copyright (c) 2020 crawl-coder <2251018029@qq.com>
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
23
  SOFTWARE.
@@ -0,0 +1,17 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt # 如果根目录有全局requirements.txt
4
+ include VERSION # 如果根目录有全局VERSION文件
5
+
6
+ # 包内文件包含
7
+ recursive-include crawlo/utils/js *
8
+ recursive-include crawlo/templates *
9
+
10
+ # 测试文件(如果需要在分发包中包含测试)
11
+ recursive-include tests *
12
+
13
+ # 排除项
14
+ global-exclude __pycache__ *.py[cod] .DS_Store *.so
15
+ global-exclude *.bak *.swp *.orig *.rej
16
+ prune samples # 排除示例目录
17
+ prune docs # 排除文档目录
@@ -1,36 +1,48 @@
1
- Metadata-Version: 2.4
2
- Name: crawlo
3
- Version: 1.0.1
4
- Summary: Crawlo是一款支持异步的python爬虫框架
5
- Home-page: https://github.com/crawl-coder/Crawlo.git
6
- Author: crawl-coder
7
- Author-email: crawlo@qq.com
8
- License: MIT
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Operating System :: OS Independent
12
- Requires-Python: >=3.6
13
- Description-Content-Type: text/markdown
14
- License-File: LICENSE
15
- Requires-Dist: aiohttp>=3.12.6
16
- Requires-Dist: httpx>=0.28.1
17
- Requires-Dist: DBUtils>=2.0
18
- Requires-Dist: parsel>=1.10.0
19
- Requires-Dist: pymysql>=1.1.1
20
- Requires-Dist: ujson>=5.10.0
21
- Provides-Extra: render
22
- Requires-Dist: webdriver-manager>=4.0.0; extra == "render"
23
- Requires-Dist: playwright; extra == "render"
24
- Requires-Dist: selenium>=3.141.0; extra == "render"
25
- Provides-Extra: all
26
- Requires-Dist: bitarray>=1.5.3; extra == "all"
27
- Requires-Dist: PyExecJS>=1.5.1; extra == "all"
28
- Requires-Dist: pymongo>=3.10.1; extra == "all"
29
- Requires-Dist: redis-py-cluster>=2.1.0; extra == "all"
30
- Requires-Dist: webdriver-manager>=4.0.0; extra == "all"
31
- Requires-Dist: playwright; extra == "all"
32
- Requires-Dist: selenium>=3.141.0; extra == "all"
33
- Dynamic: license-file
34
-
35
- # Crawlo
36
- 异步通用爬虫框架
1
+ Metadata-Version: 2.4
2
+ Name: crawlo
3
+ Version: 1.0.3
4
+ Summary: Crawlo 是一款基于异步IO的高性能Python爬虫框架,支持分布式抓取。
5
+ Home-page: https://github.com/crawl-coder/Crawlo.git
6
+ Author: crawl-coder
7
+ Author-email: crawlo@qq.com
8
+ License: MIT
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.6
13
+ Description-Content-Type: text/markdown
14
+ Requires-Dist: aiohttp>=3.12.14
15
+ Requires-Dist: aiomysql>=0.2.0
16
+ Requires-Dist: aioredis>=2.0.1
17
+ Requires-Dist: asyncmy>=0.2.10
18
+ Requires-Dist: cssselect>=1.2.0
19
+ Requires-Dist: dateparser>=1.2.2
20
+ Requires-Dist: httpx[http2]>=0.27.0
21
+ Requires-Dist: lxml>=5.2.1
22
+ Requires-Dist: motor>=3.7.0
23
+ Requires-Dist: parsel>=1.9.1
24
+ Requires-Dist: pydantic>=2.11.7
25
+ Requires-Dist: pymongo>=4.11
26
+ Requires-Dist: PyMySQL>=1.1.1
27
+ Requires-Dist: python-dateutil>=2.9.0.post0
28
+ Requires-Dist: redis>=6.2.0
29
+ Requires-Dist: requests>=2.32.4
30
+ Requires-Dist: six>=1.17.0
31
+ Requires-Dist: ujson>=5.9.0
32
+ Requires-Dist: urllib3>=2.5.0
33
+ Requires-Dist: w3lib>=2.1.2
34
+ Provides-Extra: render
35
+ Requires-Dist: webdriver-manager>=4.0.0; extra == "render"
36
+ Requires-Dist: playwright; extra == "render"
37
+ Requires-Dist: selenium>=3.141.0; extra == "render"
38
+ Provides-Extra: all
39
+ Requires-Dist: bitarray>=1.5.3; extra == "all"
40
+ Requires-Dist: PyExecJS>=1.5.1; extra == "all"
41
+ Requires-Dist: pymongo>=3.10.1; extra == "all"
42
+ Requires-Dist: redis-py-cluster>=2.1.0; extra == "all"
43
+ Requires-Dist: webdriver-manager>=4.0.0; extra == "all"
44
+ Requires-Dist: playwright; extra == "all"
45
+ Requires-Dist: selenium>=3.141.0; extra == "all"
46
+
47
+ # Crawlo
48
+ Crawlo 是一款基于异步IO的高性能Python爬虫框架,支持分布式抓取与数据管道。
crawlo-1.0.3/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # Crawlo
2
+ Crawlo 是一款基于异步IO的高性能Python爬虫框架,支持分布式抓取与数据管道。
@@ -1,6 +1,9 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- from crawlo.network.request import Request
4
- from crawlo.network.response import Response
5
- from crawlo.items.items import Item
6
- from .__version__ import __version__
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ # from crawlo.spider import Spider
4
+ from crawlo.items.items import Item
5
+ from crawlo.network.request import Request
6
+ from crawlo.network.response import Response
7
+ from crawlo.downloader import DownloaderBase
8
+ from crawlo.middleware import BaseMiddleware
9
+ from .__version__ import __version__
@@ -0,0 +1 @@
1
+ __version__ = "1.0.3"
@@ -1,2 +1,2 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
@@ -1,159 +1,159 @@
1
- #!/usr/bin/python
2
- # -*- coding:UTF-8 -*-
3
- import asyncio
4
- from inspect import iscoroutine
5
- from typing import Optional, Generator, Callable
6
-
7
- from crawlo import Request, Item
8
- from crawlo.spider import Spider
9
- from crawlo.utils.log import get_logger
10
- from crawlo.exceptions import OutputError
11
- from crawlo.core.scheduler import Scheduler
12
- from crawlo.core.processor import Processor
13
- from crawlo.task_manager import TaskManager
14
- from crawlo.utils.project import load_class
15
- from crawlo.downloader import DownloaderBase
16
- from crawlo.utils.func_tools import transform
17
- from crawlo.event import spider_opened, spider_error, request_scheduled
18
-
19
-
20
- class Engine(object):
21
-
22
- def __init__(self, crawler):
23
- self.running = False
24
- self.normal = True
25
- self.crawler = crawler
26
- self.settings = crawler.settings
27
- self.spider: Optional[Spider] = None
28
- self.downloader: Optional[DownloaderBase] = None
29
- self.scheduler: Optional[Scheduler] = None
30
- self.processor: Optional[Processor] = None
31
- self.start_requests: Optional[Generator] = None
32
- self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
33
-
34
- self.logger = get_logger(name=self.__class__.__name__)
35
-
36
- def _get_downloader_cls(self):
37
- downloader_cls = load_class(self.settings.get('DOWNLOADER'))
38
- if not issubclass(downloader_cls, DownloaderBase):
39
- raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
40
- return downloader_cls
41
-
42
- def engine_start(self):
43
- self.running = True
44
- self.logger.info(
45
- f"Crawlo (version {self.settings.get_int('VERSION')}) started. "
46
- f"(project name : {self.settings.get('PROJECT_NAME')})"
47
- )
48
-
49
- async def start_spider(self, spider):
50
- self.spider = spider
51
-
52
- self.scheduler = Scheduler.create_instance(self.crawler)
53
- if hasattr(self.scheduler, 'open'):
54
- self.scheduler.open()
55
-
56
- downloader_cls = self._get_downloader_cls()
57
- self.downloader = downloader_cls(self.crawler)
58
- if hasattr(self.downloader, 'open'):
59
- self.downloader.open()
60
-
61
- self.processor = Processor(self.crawler)
62
- if hasattr(self.processor, 'open'):
63
- self.processor.open()
64
-
65
- self.start_requests = iter(spider.start_requests())
66
- await self._open_spider()
67
-
68
- async def crawl(self):
69
- """
70
- Crawl the spider
71
- """
72
- while self.running:
73
- if request := await self._get_next_request():
74
- await self._crawl(request)
75
- try:
76
- start_request = next(self.start_requests)
77
- except StopIteration:
78
- self.start_requests = None
79
- except Exception as exp:
80
- # 1、发去请求的request全部运行完毕
81
- # 2、调度器是否空闲
82
- # 3、下载器是否空闲
83
- if not await self._exit():
84
- continue
85
- self.running = False
86
- if self.start_requests is not None:
87
- self.logger.error(f"启动请求时发生错误: {str(exp)}")
88
- else:
89
- # 请求入队
90
- await self.enqueue_request(start_request)
91
-
92
- if not self.running:
93
- await self.close_spider()
94
-
95
- async def _open_spider(self):
96
- asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
97
- crawling = asyncio.create_task(self.crawl())
98
- await crawling
99
-
100
- async def _crawl(self, request):
101
- # TODO 实现并发
102
- async def crawl_task():
103
- outputs = await self._fetch(request)
104
- # TODO 处理output
105
- if outputs:
106
- await self._handle_spider_output(outputs)
107
-
108
- # asyncio.create_task(crawl_task())
109
- self.task_manager.create_task(crawl_task())
110
-
111
- async def _fetch(self, request):
112
- async def _successful(_response):
113
- callback: Callable = request.callback or self.spider.parse
114
- if _outputs := callback(_response):
115
- if iscoroutine(_outputs):
116
- await _outputs
117
- else:
118
- return transform(_outputs, _response)
119
-
120
- _response = await self.downloader.fetch(request)
121
- if _response is None:
122
- return None
123
- output = await _successful(_response)
124
- return output
125
-
126
- async def enqueue_request(self, start_request):
127
- await self._schedule_request(start_request)
128
-
129
- async def _schedule_request(self, request):
130
- # TODO 去重
131
- if await self.scheduler.enqueue_request(request):
132
- asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
133
-
134
- async def _get_next_request(self):
135
- return await self.scheduler.next_request()
136
-
137
- async def _handle_spider_output(self, outputs):
138
- async for spider_output in outputs:
139
- if isinstance(spider_output, (Request, Item)):
140
- await self.processor.enqueue(spider_output)
141
- elif isinstance(spider_output, Exception):
142
- asyncio.create_task(
143
- self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
144
- )
145
- raise spider_output
146
- else:
147
- raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
148
-
149
- async def _exit(self):
150
- if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
151
- return True
152
- return False
153
-
154
- async def close_spider(self):
155
- await asyncio.gather(*self.task_manager.current_task)
156
- await self.scheduler.close()
157
- await self.downloader.close()
158
- if self.normal:
1
+ #!/usr/bin/python
2
+ # -*- coding:UTF-8 -*-
3
+ import asyncio
4
+ from inspect import iscoroutine
5
+ from typing import Optional, Generator, Callable
6
+
7
+ from crawlo import Request, Item
8
+ from crawlo.spider import Spider
9
+ from crawlo.utils.log import get_logger
10
+ from crawlo.exceptions import OutputError
11
+ from crawlo.core.scheduler import Scheduler
12
+ from crawlo.core.processor import Processor
13
+ from crawlo.task_manager import TaskManager
14
+ from crawlo.utils.project import load_class
15
+ from crawlo.downloader import DownloaderBase
16
+ from crawlo.utils.func_tools import transform
17
+ from crawlo.event import spider_opened, spider_error, request_scheduled
18
+
19
+
20
+ class Engine(object):
21
+
22
+ def __init__(self, crawler):
23
+ self.running = False
24
+ self.normal = True
25
+ self.crawler = crawler
26
+ self.settings = crawler.settings
27
+ self.spider: Optional[Spider] = None
28
+ self.downloader: Optional[DownloaderBase] = None
29
+ self.scheduler: Optional[Scheduler] = None
30
+ self.processor: Optional[Processor] = None
31
+ self.start_requests: Optional[Generator] = None
32
+ self.task_manager: Optional[TaskManager] = TaskManager(self.settings.get_int('CONCURRENCY'))
33
+
34
+ self.logger = get_logger(name=self.__class__.__name__)
35
+
36
+ def _get_downloader_cls(self):
37
+ downloader_cls = load_class(self.settings.get('DOWNLOADER'))
38
+ if not issubclass(downloader_cls, DownloaderBase):
39
+ raise TypeError(f'Downloader {downloader_cls.__name__} is not subclass of DownloaderBase.')
40
+ return downloader_cls
41
+
42
+ def engine_start(self):
43
+ self.running = True
44
+ self.logger.info(
45
+ f"Crawlo (version {self.settings.get_int('VERSION')}) started. "
46
+ f"(project name : {self.settings.get('PROJECT_NAME')})"
47
+ )
48
+
49
+ async def start_spider(self, spider):
50
+ self.spider = spider
51
+
52
+ self.scheduler = Scheduler.create_instance(self.crawler)
53
+ if hasattr(self.scheduler, 'open'):
54
+ self.scheduler.open()
55
+
56
+ downloader_cls = self._get_downloader_cls()
57
+ self.downloader = downloader_cls(self.crawler)
58
+ if hasattr(self.downloader, 'open'):
59
+ self.downloader.open()
60
+
61
+ self.processor = Processor(self.crawler)
62
+ if hasattr(self.processor, 'open'):
63
+ self.processor.open()
64
+
65
+ self.start_requests = iter(spider.start_requests())
66
+ await self._open_spider()
67
+
68
+ async def crawl(self):
69
+ """
70
+ Crawl the spider
71
+ """
72
+ while self.running:
73
+ if request := await self._get_next_request():
74
+ await self._crawl(request)
75
+ try:
76
+ start_request = next(self.start_requests)
77
+ except StopIteration:
78
+ self.start_requests = None
79
+ except Exception as exp:
80
+ # 1、发去请求的request全部运行完毕
81
+ # 2、调度器是否空闲
82
+ # 3、下载器是否空闲
83
+ if not await self._exit():
84
+ continue
85
+ self.running = False
86
+ if self.start_requests is not None:
87
+ self.logger.error(f"启动请求时发生错误: {str(exp)}")
88
+ else:
89
+ # 请求入队
90
+ await self.enqueue_request(start_request)
91
+
92
+ if not self.running:
93
+ await self.close_spider()
94
+
95
+ async def _open_spider(self):
96
+ asyncio.create_task(self.crawler.subscriber.notify(spider_opened))
97
+ crawling = asyncio.create_task(self.crawl())
98
+ await crawling
99
+
100
+ async def _crawl(self, request):
101
+ # TODO 实现并发
102
+ async def crawl_task():
103
+ outputs = await self._fetch(request)
104
+ # TODO 处理output
105
+ if outputs:
106
+ await self._handle_spider_output(outputs)
107
+
108
+ # asyncio.create_task(crawl_task())
109
+ self.task_manager.create_task(crawl_task())
110
+
111
+ async def _fetch(self, request):
112
+ async def _successful(_response):
113
+ callback: Callable = request.callback or self.spider.parse
114
+ if _outputs := callback(_response):
115
+ if iscoroutine(_outputs):
116
+ await _outputs
117
+ else:
118
+ return transform(_outputs, _response)
119
+
120
+ _response = await self.downloader.fetch(request)
121
+ if _response is None:
122
+ return None
123
+ output = await _successful(_response)
124
+ return output
125
+
126
+ async def enqueue_request(self, start_request):
127
+ await self._schedule_request(start_request)
128
+
129
+ async def _schedule_request(self, request):
130
+ # TODO 去重
131
+ if await self.scheduler.enqueue_request(request):
132
+ asyncio.create_task(self.crawler.subscriber.notify(request_scheduled, request, self.crawler.spider))
133
+
134
+ async def _get_next_request(self):
135
+ return await self.scheduler.next_request()
136
+
137
+ async def _handle_spider_output(self, outputs):
138
+ async for spider_output in outputs:
139
+ if isinstance(spider_output, (Request, Item)):
140
+ await self.processor.enqueue(spider_output)
141
+ elif isinstance(spider_output, Exception):
142
+ asyncio.create_task(
143
+ self.crawler.subscriber.notify(spider_error, spider_output, self.spider)
144
+ )
145
+ raise spider_output
146
+ else:
147
+ raise OutputError(f'{type(self.spider)} must return `Request` or `Item`.')
148
+
149
+ async def _exit(self):
150
+ if self.scheduler.idle() and self.downloader.idle() and self.task_manager.all_done() and self.processor.idle():
151
+ return True
152
+ return False
153
+
154
+ async def close_spider(self):
155
+ await asyncio.gather(*self.task_manager.current_task)
156
+ await self.scheduler.close()
157
+ await self.downloader.close()
158
+ if self.normal:
159
159
  await self.crawler.close()
@@ -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()