crawlo 1.3.1__py3-none-any.whl → 1.3.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.

Files changed (219) hide show
  1. crawlo/__init__.py +63 -63
  2. crawlo/__version__.py +1 -1
  3. crawlo/cli.py +75 -75
  4. crawlo/commands/__init__.py +14 -14
  5. crawlo/commands/check.py +594 -594
  6. crawlo/commands/genspider.py +151 -151
  7. crawlo/commands/help.py +138 -138
  8. crawlo/commands/list.py +155 -155
  9. crawlo/commands/run.py +322 -314
  10. crawlo/commands/startproject.py +436 -436
  11. crawlo/commands/stats.py +187 -187
  12. crawlo/commands/utils.py +196 -196
  13. crawlo/config.py +312 -312
  14. crawlo/config_validator.py +277 -277
  15. crawlo/core/__init__.py +2 -2
  16. crawlo/core/engine.py +365 -365
  17. crawlo/core/processor.py +40 -40
  18. crawlo/core/scheduler.py +256 -256
  19. crawlo/crawler.py +1166 -1168
  20. crawlo/data/__init__.py +5 -5
  21. crawlo/data/user_agents.py +194 -194
  22. crawlo/downloader/__init__.py +273 -273
  23. crawlo/downloader/aiohttp_downloader.py +226 -226
  24. crawlo/downloader/cffi_downloader.py +245 -245
  25. crawlo/downloader/httpx_downloader.py +259 -259
  26. crawlo/downloader/hybrid_downloader.py +212 -212
  27. crawlo/downloader/playwright_downloader.py +402 -402
  28. crawlo/downloader/selenium_downloader.py +472 -472
  29. crawlo/event.py +11 -11
  30. crawlo/exceptions.py +81 -81
  31. crawlo/extension/__init__.py +39 -39
  32. crawlo/extension/health_check.py +141 -141
  33. crawlo/extension/log_interval.py +57 -57
  34. crawlo/extension/log_stats.py +81 -81
  35. crawlo/extension/logging_extension.py +52 -45
  36. crawlo/extension/memory_monitor.py +104 -104
  37. crawlo/extension/performance_profiler.py +133 -133
  38. crawlo/extension/request_recorder.py +107 -107
  39. crawlo/filters/__init__.py +154 -154
  40. crawlo/filters/aioredis_filter.py +234 -234
  41. crawlo/filters/memory_filter.py +269 -269
  42. crawlo/items/__init__.py +23 -23
  43. crawlo/items/base.py +21 -21
  44. crawlo/items/fields.py +52 -52
  45. crawlo/items/items.py +104 -104
  46. crawlo/middleware/__init__.py +21 -21
  47. crawlo/middleware/default_header.py +132 -132
  48. crawlo/middleware/download_delay.py +104 -104
  49. crawlo/middleware/middleware_manager.py +135 -135
  50. crawlo/middleware/offsite.py +123 -115
  51. crawlo/middleware/proxy.py +386 -386
  52. crawlo/middleware/request_ignore.py +86 -86
  53. crawlo/middleware/response_code.py +163 -163
  54. crawlo/middleware/response_filter.py +136 -136
  55. crawlo/middleware/retry.py +124 -124
  56. crawlo/middleware/simple_proxy.py +65 -65
  57. crawlo/mode_manager.py +187 -148
  58. crawlo/network/__init__.py +21 -21
  59. crawlo/network/request.py +379 -379
  60. crawlo/network/response.py +359 -359
  61. crawlo/pipelines/__init__.py +21 -21
  62. crawlo/pipelines/bloom_dedup_pipeline.py +156 -156
  63. crawlo/pipelines/console_pipeline.py +39 -39
  64. crawlo/pipelines/csv_pipeline.py +316 -316
  65. crawlo/pipelines/database_dedup_pipeline.py +222 -222
  66. crawlo/pipelines/json_pipeline.py +218 -218
  67. crawlo/pipelines/memory_dedup_pipeline.py +115 -115
  68. crawlo/pipelines/mongo_pipeline.py +131 -131
  69. crawlo/pipelines/mysql_pipeline.py +318 -318
  70. crawlo/pipelines/pipeline_manager.py +75 -75
  71. crawlo/pipelines/redis_dedup_pipeline.py +166 -166
  72. crawlo/project.py +325 -297
  73. crawlo/queue/pqueue.py +37 -37
  74. crawlo/queue/queue_manager.py +379 -379
  75. crawlo/queue/redis_priority_queue.py +306 -306
  76. crawlo/settings/__init__.py +7 -7
  77. crawlo/settings/default_settings.py +225 -225
  78. crawlo/settings/setting_manager.py +198 -198
  79. crawlo/spider/__init__.py +639 -639
  80. crawlo/stats_collector.py +59 -59
  81. crawlo/subscriber.py +129 -129
  82. crawlo/task_manager.py +30 -30
  83. crawlo/templates/crawlo.cfg.tmpl +10 -10
  84. crawlo/templates/project/__init__.py.tmpl +3 -3
  85. crawlo/templates/project/items.py.tmpl +17 -17
  86. crawlo/templates/project/middlewares.py.tmpl +118 -118
  87. crawlo/templates/project/pipelines.py.tmpl +96 -96
  88. crawlo/templates/project/settings.py.tmpl +266 -261
  89. crawlo/templates/project/settings_distributed.py.tmpl +179 -174
  90. crawlo/templates/project/settings_gentle.py.tmpl +60 -95
  91. crawlo/templates/project/settings_high_performance.py.tmpl +130 -125
  92. crawlo/templates/project/settings_minimal.py.tmpl +34 -29
  93. crawlo/templates/project/settings_simple.py.tmpl +101 -96
  94. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  95. crawlo/templates/run.py.tmpl +38 -47
  96. crawlo/templates/spider/spider.py.tmpl +143 -143
  97. crawlo/tools/__init__.py +200 -200
  98. crawlo/tools/anti_crawler.py +268 -268
  99. crawlo/tools/authenticated_proxy.py +240 -240
  100. crawlo/tools/data_formatter.py +225 -225
  101. crawlo/tools/data_validator.py +180 -180
  102. crawlo/tools/date_tools.py +289 -289
  103. crawlo/tools/distributed_coordinator.py +388 -388
  104. crawlo/tools/encoding_converter.py +127 -127
  105. crawlo/tools/request_tools.py +82 -82
  106. crawlo/tools/retry_mechanism.py +224 -224
  107. crawlo/tools/scenario_adapter.py +262 -262
  108. crawlo/tools/text_cleaner.py +232 -232
  109. crawlo/utils/__init__.py +34 -34
  110. crawlo/utils/batch_processor.py +259 -259
  111. crawlo/utils/controlled_spider_mixin.py +439 -439
  112. crawlo/utils/db_helper.py +343 -343
  113. crawlo/utils/enhanced_error_handler.py +356 -356
  114. crawlo/utils/env_config.py +142 -142
  115. crawlo/utils/error_handler.py +123 -123
  116. crawlo/utils/func_tools.py +82 -82
  117. crawlo/utils/large_scale_config.py +286 -286
  118. crawlo/utils/large_scale_helper.py +344 -344
  119. crawlo/utils/log.py +199 -146
  120. crawlo/utils/performance_monitor.py +285 -285
  121. crawlo/utils/queue_helper.py +175 -175
  122. crawlo/utils/redis_connection_pool.py +351 -351
  123. crawlo/utils/redis_key_validator.py +198 -198
  124. crawlo/utils/request.py +267 -267
  125. crawlo/utils/request_serializer.py +218 -218
  126. crawlo/utils/spider_loader.py +61 -61
  127. crawlo/utils/system.py +11 -11
  128. crawlo/utils/tools.py +4 -4
  129. crawlo/utils/url.py +39 -39
  130. {crawlo-1.3.1.dist-info → crawlo-1.3.3.dist-info}/METADATA +1020 -1020
  131. crawlo-1.3.3.dist-info/RECORD +219 -0
  132. examples/__init__.py +7 -7
  133. tests/DOUBLE_CRAWLO_PREFIX_FIX_REPORT.md +81 -81
  134. tests/__init__.py +7 -7
  135. tests/advanced_tools_example.py +275 -275
  136. tests/authenticated_proxy_example.py +107 -107
  137. tests/cleaners_example.py +160 -160
  138. tests/config_validation_demo.py +142 -142
  139. tests/controlled_spider_example.py +205 -205
  140. tests/date_tools_example.py +180 -180
  141. tests/debug_pipelines.py +66 -66
  142. tests/dynamic_loading_example.py +523 -523
  143. tests/dynamic_loading_test.py +104 -104
  144. tests/env_config_example.py +133 -133
  145. tests/error_handling_example.py +171 -171
  146. tests/redis_key_validation_demo.py +130 -130
  147. tests/request_params_example.py +150 -150
  148. tests/response_improvements_example.py +144 -144
  149. tests/test_advanced_tools.py +148 -148
  150. tests/test_all_redis_key_configs.py +145 -145
  151. tests/test_authenticated_proxy.py +141 -141
  152. tests/test_cleaners.py +54 -54
  153. tests/test_comprehensive.py +146 -146
  154. tests/test_config_consistency.py +80 -80
  155. tests/test_config_merge.py +152 -152
  156. tests/test_config_validator.py +182 -182
  157. tests/test_crawlo_proxy_integration.py +108 -108
  158. tests/test_date_tools.py +123 -123
  159. tests/test_default_header_middleware.py +158 -158
  160. tests/test_distributed.py +65 -65
  161. tests/test_double_crawlo_fix.py +207 -207
  162. tests/test_double_crawlo_fix_simple.py +124 -124
  163. tests/test_download_delay_middleware.py +221 -221
  164. tests/test_downloader_proxy_compatibility.py +268 -268
  165. tests/test_dynamic_downloaders_proxy.py +124 -124
  166. tests/test_dynamic_proxy.py +92 -92
  167. tests/test_dynamic_proxy_config.py +146 -146
  168. tests/test_dynamic_proxy_real.py +109 -109
  169. tests/test_edge_cases.py +303 -303
  170. tests/test_enhanced_error_handler.py +270 -270
  171. tests/test_env_config.py +121 -121
  172. tests/test_error_handler_compatibility.py +112 -112
  173. tests/test_final_validation.py +153 -153
  174. tests/test_framework_env_usage.py +103 -103
  175. tests/test_integration.py +169 -169
  176. tests/test_item_dedup_redis_key.py +122 -122
  177. tests/test_mode_consistency.py +51 -51
  178. tests/test_offsite_middleware.py +221 -221
  179. tests/test_parsel.py +29 -29
  180. tests/test_performance.py +327 -327
  181. tests/test_proxy_api.py +264 -264
  182. tests/test_proxy_health_check.py +32 -32
  183. tests/test_proxy_middleware.py +121 -121
  184. tests/test_proxy_middleware_enhanced.py +216 -216
  185. tests/test_proxy_middleware_integration.py +136 -136
  186. tests/test_proxy_middleware_refactored.py +184 -184
  187. tests/test_proxy_providers.py +56 -56
  188. tests/test_proxy_stats.py +19 -19
  189. tests/test_proxy_strategies.py +59 -59
  190. tests/test_queue_manager_double_crawlo.py +173 -173
  191. tests/test_queue_manager_redis_key.py +176 -176
  192. tests/test_random_user_agent.py +72 -72
  193. tests/test_real_scenario_proxy.py +195 -195
  194. tests/test_redis_config.py +28 -28
  195. tests/test_redis_connection_pool.py +294 -294
  196. tests/test_redis_key_naming.py +181 -181
  197. tests/test_redis_key_validator.py +123 -123
  198. tests/test_redis_queue.py +224 -224
  199. tests/test_request_ignore_middleware.py +182 -182
  200. tests/test_request_params.py +111 -111
  201. tests/test_request_serialization.py +70 -70
  202. tests/test_response_code_middleware.py +349 -349
  203. tests/test_response_filter_middleware.py +427 -427
  204. tests/test_response_improvements.py +152 -152
  205. tests/test_retry_middleware.py +241 -241
  206. tests/test_scheduler.py +252 -252
  207. tests/test_scheduler_config_update.py +133 -133
  208. tests/test_simple_response.py +61 -61
  209. tests/test_telecom_spider_redis_key.py +205 -205
  210. tests/test_template_content.py +87 -87
  211. tests/test_template_redis_key.py +134 -134
  212. tests/test_tools.py +159 -159
  213. tests/test_user_agents.py +96 -96
  214. tests/tools_example.py +260 -260
  215. tests/verify_distributed.py +117 -117
  216. crawlo-1.3.1.dist-info/RECORD +0 -219
  217. {crawlo-1.3.1.dist-info → crawlo-1.3.3.dist-info}/WHEEL +0 -0
  218. {crawlo-1.3.1.dist-info → crawlo-1.3.3.dist-info}/entry_points.txt +0 -0
  219. {crawlo-1.3.1.dist-info → crawlo-1.3.3.dist-info}/top_level.txt +0 -0
@@ -1,1020 +1,1020 @@
1
- Metadata-Version: 2.4
2
- Name: crawlo
3
- Version: 1.3.1
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: curl-cffi>=0.13.0
22
- Requires-Dist: lxml>=5.2.1
23
- Requires-Dist: motor>=3.7.0
24
- Requires-Dist: parsel>=1.9.1
25
- Requires-Dist: pydantic>=2.11.7
26
- Requires-Dist: pymongo>=4.11
27
- Requires-Dist: PyMySQL>=1.1.1
28
- Requires-Dist: python-dateutil>=2.9.0.post0
29
- Requires-Dist: redis>=6.2.0
30
- Requires-Dist: requests>=2.32.4
31
- Requires-Dist: six>=1.17.0
32
- Requires-Dist: ujson>=5.9.0
33
- Requires-Dist: urllib3>=2.5.0
34
- Requires-Dist: w3lib>=2.1.2
35
- Requires-Dist: rich>=14.1.0
36
- Requires-Dist: astor>=0.8.1
37
- Requires-Dist: watchdog>=6.0.0
38
- Provides-Extra: render
39
- Requires-Dist: webdriver-manager>=4.0.0; extra == "render"
40
- Requires-Dist: playwright; extra == "render"
41
- Requires-Dist: selenium>=3.141.0; extra == "render"
42
- Provides-Extra: all
43
- Requires-Dist: bitarray>=1.5.3; extra == "all"
44
- Requires-Dist: PyExecJS>=1.5.1; extra == "all"
45
- Requires-Dist: pymongo>=3.10.1; extra == "all"
46
- Requires-Dist: redis-py-cluster>=2.1.0; extra == "all"
47
- Requires-Dist: webdriver-manager>=4.0.0; extra == "all"
48
- Requires-Dist: playwright; extra == "all"
49
- Requires-Dist: selenium>=3.141.0; extra == "all"
50
-
51
- <!-- markdownlint-disable MD033 MD041 -->
52
- <div align="center">
53
- <h1 align="center">Crawlo</h1>
54
- <p align="center">异步分布式爬虫框架</p>
55
- <p align="center"><strong>基于 asyncio 的高性能异步分布式爬虫框架,支持单机和分布式部署</strong></p>
56
-
57
- <p align="center">
58
- <a href="https://www.python.org/downloads/">
59
- <img src="https://img.shields.io/badge/python-%3C%3D3.12-blue" alt="Python Version">
60
- </a>
61
- <a href="LICENSE">
62
- <img src="https://img.shields.io/badge/license-MIT-green" alt="License">
63
- </a>
64
- <a href="https://crawlo.readthedocs.io/">
65
- <img src="https://img.shields.io/badge/docs-latest-brightgreen" alt="Documentation">
66
- </a>
67
- <a href="https://github.com/crawlo/crawlo/actions">
68
- <img src="https://github.com/crawlo/crawlo/workflows/CI/badge.svg" alt="CI Status">
69
- </a>
70
- </p>
71
-
72
- <p align="center">
73
- <a href="#-特性">特性</a> •
74
- <a href="#-快速开始">快速开始</a> •
75
- <a href="#-命令行工具">命令行工具</a> •
76
- <a href="#-示例项目">示例项目</a>
77
- </p>
78
- </div>
79
-
80
- <br />
81
-
82
- <!-- 特性 section -->
83
- <div align="center">
84
- <h2>🌟 特性</h2>
85
-
86
- <table>
87
- <thead>
88
- <tr>
89
- <th>特性</th>
90
- <th>描述</th>
91
- </tr>
92
- </thead>
93
- <tbody>
94
- <tr>
95
- <td>⚡ <strong>异步高性能</strong></td>
96
- <td>基于 asyncio 实现,充分利用现代 CPU 夯性能</td>
97
- </tr>
98
- <tr>
99
- <td>🌐 <strong>分布式支持</strong></td>
100
- <td>内置 Redis 队列,轻松实现分布式部署</td>
101
- </tr>
102
- <tr>
103
- <td>🔧 <strong>模块化设计</strong></td>
104
- <td>中间件、管道、扩展组件系统,易于定制和扩展</td>
105
- </tr>
106
- <tr>
107
- <td>🔄 <strong>智能去重</strong></td>
108
- <td>多种去重策略(内存、Redis、Bloom Filter)</td>
109
- </tr>
110
- <tr>
111
- <td>⚙️ <strong>灵活配置</strong></td>
112
- <td>支持多种配置方式,适应不同场景需求</td>
113
- </tr>
114
- <tr>
115
- <td>📋 <strong>高级日志</strong></td>
116
- <td>支持日志轮转、结构化日志、JSON格式等高级功能</td>
117
- </tr>
118
- <tr>
119
- <td>📚 <strong>丰富文档</strong></td>
120
- <td>完整的中英文双语文档和示例项目</td>
121
- </tr>
122
- </tbody>
123
- </table>
124
- </div>
125
-
126
- <br />
127
-
128
- ---
129
-
130
- <!-- 快速开始 section -->
131
- <h2 align="center">🚀 快速开始</h2>
132
-
133
- ### 安装
134
-
135
- ```bash
136
- pip install crawlo
137
- ```
138
-
139
- ### 创建项目
140
-
141
- ```bash
142
- # 创建默认项目
143
- crawlo startproject myproject
144
-
145
- # 创建分布式模板项目
146
- crawlo startproject myproject distributed
147
-
148
- # 创建项目并选择特定模块
149
- crawlo startproject myproject --modules mysql,redis,proxy
150
-
151
- cd myproject
152
- ```
153
-
154
- ### 生成爬虫
155
-
156
- ```bash
157
- # 在项目目录中生成爬虫
158
- crawlo genspider news_spider news.example.com
159
- ```
160
-
161
- ### 编写爬虫
162
-
163
- ``python
164
- from crawlo import Spider, Request, Item
165
-
166
- class MyItem(Item):
167
- title = ''
168
- url = ''
169
-
170
- class MySpider(Spider):
171
- name = 'myspider'
172
-
173
- async def start_requests(self):
174
- yield Request('https://httpbin.org/get', callback=self.parse)
175
-
176
- async def parse(self, response):
177
- yield MyItem(
178
- title='Example Title',
179
- url=response.url
180
- )
181
- ```
182
-
183
- ### 运行爬虫
184
-
185
- ```bash
186
- # 使用命令行工具运行爬虫(推荐)
187
- crawlo run myspider
188
-
189
- # 使用项目自带的 run.py 脚本运行
190
- python run.py
191
-
192
- # 运行所有爬虫
193
- crawlo run all
194
-
195
- # 在项目子目录中也能正确运行
196
- cd subdirectory
197
- crawlo run myspider
198
- ```
199
-
200
- ---
201
-
202
- <!-- 命令行工具 section -->
203
- <h2 align="center">🔧 命令行工具</h2>
204
-
205
- Crawlo 提供了丰富的命令行工具,简化项目创建和管理。
206
-
207
- ### crawlo startproject
208
-
209
- 创建新的爬虫项目。
210
-
211
- ```bash
212
- # 创建默认项目
213
- crawlo startproject myproject
214
-
215
- # 创建指定模板的项目
216
- crawlo startproject myproject simple
217
- crawlo startproject myproject distributed
218
- ```
219
-
220
- ### crawlo genspider
221
-
222
- 在现有项目中生成新的爬虫。
223
-
224
- ```bash
225
- # 在当前目录生成爬虫
226
- crawlo genspider myspider http://example.com
227
-
228
- # 指定模板生成爬虫
229
- crawlo genspider myspider http://example.com --template basic
230
- ```
231
-
232
- ### crawlo run
233
-
234
- 运行指定的爬虫。
235
-
236
- ```bash
237
- # 运行单个爬虫
238
- crawlo run myspider
239
-
240
- # 运行所有爬虫
241
- crawlo run all
242
-
243
- # 以JSON格式输出结果
244
- crawlo run myspider --json
245
-
246
- # 禁用统计信息
247
- crawlo run myspider --no-stats
248
- ```
249
-
250
- ### crawlo list
251
-
252
- 列出项目中的所有爬虫。
253
-
254
- ```bash
255
- crawlo list
256
- ```
257
-
258
- ### crawlo check
259
-
260
- 检查项目配置和爬虫实现。
261
-
262
- ```bash
263
- # 检查所有爬虫
264
- crawlo check
265
-
266
- # 检查特定爬虫
267
- crawlo check myspider
268
- ```
269
-
270
- ### crawlo stats
271
-
272
- 查看爬虫统计信息。
273
-
274
- ```bash
275
- # 查看统计信息
276
- crawlo stats
277
- ```
278
-
279
- ---
280
-
281
- <!-- 配置方式 section -->
282
- <h2 align="center">⚙️ 配置方式</h2>
283
-
284
- Crawlo 提供了多种灵活的配置方式,以适应不同的使用场景和开发需求。
285
-
286
- ### 三种配置方式详解
287
-
288
- #### 1. 配置工厂方式(推荐)
289
-
290
- 使用 `CrawloConfig` 配置工厂是推荐的配置方式,它提供了类型安全和智能提示。
291
-
292
- ```python
293
- from crawlo.config import CrawloConfig
294
- from crawlo.crawler import CrawlerProcess
295
-
296
- # 单机模式配置
297
- config = CrawloConfig.standalone(
298
- concurrency=8,
299
- download_delay=1.0
300
- )
301
-
302
- # 分布式模式配置
303
- config = CrawloConfig.distributed(
304
- redis_host='127.0.0.1',
305
- redis_port=6379,
306
- project_name='myproject',
307
- concurrency=16
308
- )
309
-
310
- # 自动检测模式配置
311
- config = CrawloConfig.auto(concurrency=12)
312
-
313
- # 从环境变量读取配置
314
- config = CrawloConfig.from_env()
315
-
316
- # 创建爬虫进程
317
- process = CrawlerProcess(settings=config.to_dict())
318
- ```
319
-
320
- #### 2. 直接配置方式
321
-
322
- 直接在 `settings.py` 文件中配置各项参数,适合需要精细控制的场景。
323
-
324
- ```
325
- # settings.py
326
- PROJECT_NAME = 'myproject'
327
- RUN_MODE = 'standalone' # 或 'distributed' 或 'auto'
328
- CONCURRENCY = 8
329
- DOWNLOAD_DELAY = 1.0
330
-
331
- # 分布式模式下需要配置Redis
332
- REDIS_HOST = '127.0.0.1'
333
- REDIS_PORT = 6379
334
- REDIS_PASSWORD = ''
335
-
336
- # 其他配置...
337
- ```
338
-
339
- #### 3. 环境变量方式
340
-
341
- 通过环境变量配置,适合部署和CI/CD场景。
342
-
343
- ```bash
344
- # 设置环境变量
345
- export CRAWLO_MODE=standalone
346
- export CONCURRENCY=8
347
- export DOWNLOAD_DELAY=1.0
348
- export REDIS_HOST=127.0.0.1
349
- export REDIS_PORT=6379
350
- ```
351
-
352
- ```python
353
- # 在代码中读取环境变量
354
- from crawlo.config import CrawloConfig
355
- config = CrawloConfig.from_env()
356
- process = CrawlerProcess(settings=config.to_dict())
357
- ```
358
-
359
- ### 不同运行模式下的最佳配置方式
360
-
361
- #### 单机模式 (standalone)
362
-
363
- 适用于开发调试、小规模数据采集、个人项目。
364
-
365
- **推荐配置方式:**
366
- ```python
367
- from crawlo.config import CrawloConfig
368
- config = CrawloConfig.standalone(concurrency=4, download_delay=1.0)
369
- process = CrawlerProcess(settings=config.to_dict())
370
- ```
371
-
372
- **特点:**
373
- - 简单易用,资源占用少
374
- - 无需额外依赖(如Redis)
375
- - 适合个人开发环境
376
-
377
- #### 分布式模式 (distributed)
378
-
379
- 适用于大规模数据采集、多节点协同工作、高并发需求。
380
-
381
- **推荐配置方式:**
382
- ```python
383
- from crawlo.config import CrawloConfig
384
- config = CrawloConfig.distributed(
385
- redis_host='your_redis_host',
386
- redis_port=6379,
387
- project_name='myproject',
388
- concurrency=16
389
- )
390
- process = CrawlerProcess(settings=config.to_dict())
391
- ```
392
-
393
- **特点:**
394
- - 支持多节点扩展
395
- - 高并发处理能力
396
- - 需要Redis支持
397
-
398
- #### 自动检测模式 (auto)
399
-
400
- 适用于希望根据环境自动选择最佳运行方式。
401
-
402
- **推荐配置方式:**
403
- ```python
404
- from crawlo.config import CrawloConfig
405
- config = CrawloConfig.auto(concurrency=12)
406
- process = CrawlerProcess(settings=config.to_dict())
407
- ```
408
-
409
- **特点:**
410
- - 智能检测环境配置
411
- - 自动选择运行模式
412
- - 适合在不同环境中使用同一套配置
413
-
414
- ### 组件配置说明
415
-
416
- Crawlo框架的中间件、管道和扩展组件采用模块化设计,框架会自动加载默认组件,用户只需配置自定义组件。
417
-
418
- #### 中间件配置
419
-
420
- 框架默认加载以下中间件:
421
- - RequestIgnoreMiddleware:忽略无效请求
422
- - DownloadDelayMiddleware:控制请求频率
423
- - DefaultHeaderMiddleware:添加默认请求头
424
- - ProxyMiddleware:设置代理
425
- - OffsiteMiddleware:站外请求过滤
426
- - RetryMiddleware:失败请求重试
427
- - ResponseCodeMiddleware:处理特殊状态码
428
- - ResponseFilterMiddleware:响应内容过滤
429
-
430
- 用户可以通过`CUSTOM_MIDDLEWARES`配置自定义中间件:
431
-
432
- ``python
433
- # settings.py
434
- CUSTOM_MIDDLEWARES = [
435
- 'myproject.middlewares.CustomMiddleware',
436
- ]
437
- ```
438
-
439
- > **注意**:DefaultHeaderMiddleware 和 OffsiteMiddleware 需要相应的配置才能启用:
440
- > - DefaultHeaderMiddleware 需要配置 `DEFAULT_REQUEST_HEADERS` 或 `USER_AGENT` 参数
441
- > - OffsiteMiddleware 需要配置 `ALLOWED_DOMAINS` 参数
442
- >
443
- > 如果未配置相应参数,这些中间件会因为 NotConfiguredError 而被禁用。
444
-
445
- > **注意**:中间件的顺序很重要。SimpleProxyMiddleware 通常放在列表末尾,
446
- > 这样可以在所有默认中间件处理后再应用代理设置。
447
-
448
- #### 管道配置
449
-
450
- 框架默认加载以下管道:
451
- - ConsolePipeline:控制台输出
452
- - 默认去重管道(根据运行模式自动选择)
453
-
454
- 用户可以通过`CUSTOM_PIPELINES`配置自定义管道:
455
-
456
- ```python
457
- # settings.py
458
- CUSTOM_PIPELINES = [
459
- 'crawlo.pipelines.json_pipeline.JsonPipeline',
460
- 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline',
461
- ]
462
- ```
463
-
464
- #### 扩展配置
465
-
466
- 框架默认加载以下扩展:
467
- - LogIntervalExtension:定时日志
468
- - LogStats:统计信息
469
- - CustomLoggerExtension:自定义日志
470
-
471
- 用户可以通过`CUSTOM_EXTENSIONS`配置自定义扩展:
472
-
473
- ```python
474
- # settings.py
475
- CUSTOM_EXTENSIONS = [
476
- 'crawlo.extension.memory_monitor.MemoryMonitorExtension',
477
- ]
478
- ```
479
-
480
- <!-- 架构设计 section -->
481
- <h2 align="center">🏗️ 架构设计</h2>
482
-
483
- ### 核心组件说明
484
-
485
- Crawlo 框架由以下核心组件构成:
486
-
487
- <table>
488
- <thead>
489
- <tr>
490
- <th>组件</th>
491
- <th>功能描述</th>
492
- </tr>
493
- </thead>
494
- <tbody>
495
- <tr>
496
- <td><strong>Crawler</strong></td>
497
- <td>爬虫运行实例,管理Spider与引擎的生命周期</td>
498
- </tr>
499
- <tr>
500
- <td><strong>Engine</strong></td>
501
- <td>引擎组件,协调Scheduler、Downloader、Processor</td>
502
- </tr>
503
- <tr>
504
- <td><strong>Scheduler</strong></td>
505
- <td>调度器,管理请求队列和去重过滤</td>
506
- </tr>
507
- <tr>
508
- <td><strong>Downloader</strong></td>
509
- <td>下载器,负责网络请求,支持多种实现(aiohttp, httpx, curl-cffi)</td>
510
- </tr>
511
- <tr>
512
- <td><strong>Processor</strong></td>
513
- <td>处理器,处理响应数据和管道</td>
514
- </tr>
515
- <tr>
516
- <td><strong>QueueManager</strong></td>
517
- <td>统一的队列管理器,支持内存队列和Redis队列的自动切换</td>
518
- </tr>
519
- <tr>
520
- <td><strong>Filter</strong></td>
521
- <td>请求去重过滤器,支持内存和Redis两种实现</td>
522
- </tr>
523
- <tr>
524
- <td><strong>Middleware</strong></td>
525
- <td>中间件系统,处理请求/响应的预处理和后处理</td>
526
- </tr>
527
- <tr>
528
- <td><strong>Pipeline</strong></td>
529
- <td>数据处理管道,支持多种存储方式(控制台、数据库等)和去重功能</td>
530
- </tr>
531
- <tr>
532
- <td><strong>Spider</strong></td>
533
- <td>爬虫基类,定义爬取逻辑</td>
534
- </tr>
535
- </tbody>
536
- </table>
537
-
538
- ### 运行模式
539
-
540
- Crawlo支持三种运行模式:
541
-
542
- <table>
543
- <thead>
544
- <tr>
545
- <th>模式</th>
546
- <th>描述</th>
547
- <th>队列类型</th>
548
- <th>过滤器类型</th>
549
- </tr>
550
- </thead>
551
- <tbody>
552
- <tr>
553
- <td><strong>standalone</strong></td>
554
- <td>单机模式</td>
555
- <td>内存队列</td>
556
- <td>内存过滤器</td>
557
- </tr>
558
- <tr>
559
- <td><strong>distributed</strong></td>
560
- <td>分布式模式</td>
561
- <td>Redis队列</td>
562
- <td>Redis过滤器</td>
563
- </tr>
564
- <tr>
565
- <td><strong>auto</strong></td>
566
- <td>自动检测模式</td>
567
- <td>根据环境自动选择最佳运行方式</td>
568
- <td>根据环境自动选择</td>
569
- </tr>
570
- </tbody>
571
- </table>
572
-
573
- > **运行模式说明**: distributed模式为多节点分布式设计,强制使用Redis队列和去重;standalone+auto为单机智能模式,根据环境自动选择内存或Redis队列与去重策略,零配置启动。
574
-
575
- #### 运行模式选择指南
576
-
577
- ##### 1. 单机模式 (standalone)
578
- - **适用场景**:
579
- - 开发和测试阶段
580
- - 小规模数据采集(几千到几万条数据)
581
- - 学习和演示用途
582
- - 对目标网站负载要求不高的场景
583
- - **优势**:
584
- - 配置简单,无需额外依赖
585
- - 资源消耗低
586
- - 启动快速
587
- - 适合本地开发调试
588
- - **限制**:
589
- - 无法跨会话去重
590
- - 无法分布式部署
591
- - 内存占用随数据量增长
592
-
593
- ##### 2. 分布式模式 (distributed)
594
- - **适用场景**:
595
- - 大规模数据采集(百万级以上)
596
- - 需要多节点协同工作
597
- - 要求跨会话、跨节点去重
598
- - 生产环境部署
599
- - **优势**:
600
- - 支持水平扩展
601
- - 跨节点任务协调
602
- - 持久化去重过滤
603
- - 高可用性
604
- - **要求**:
605
- - 需要Redis服务器
606
- - 网络环境稳定
607
- - 更复杂的配置管理
608
-
609
- ##### 3. 自动模式 (auto)
610
- - **适用场景**:
611
- - 希望根据环境自动选择最佳配置
612
- - 开发和生产环境使用同一套代码
613
- - 动态适应运行环境
614
- - **工作机制**:
615
- - 检测Redis可用性
616
- - Redis可用时自动切换到分布式模式
617
- - Redis不可用时回退到单机模式
618
- - **优势**:
619
- - 环境适应性强
620
- - 部署灵活
621
- - 开发和生产环境配置统一
622
-
623
- #### 队列类型选择指南
624
-
625
- Crawlo支持三种队列类型,可通过`QUEUE_TYPE`配置项设置:
626
-
627
- - **memory**:使用内存队列,适用于单机模式
628
- - **redis**:使用Redis队列,适用于分布式模式
629
- - **auto**:自动检测模式,根据Redis可用性自动选择
630
-
631
- 推荐使用`auto`模式,让框架根据环境自动选择最适合的队列类型。
632
-
633
- <!-- 配置系统 section -->
634
- <h2 align="center">🎛️ 配置系统</h2>
635
-
636
- ### 传统配置方式
637
-
638
- ```
639
- # settings.py
640
- PROJECT_NAME = 'myproject'
641
- CONCURRENCY = 16
642
- DOWNLOAD_DELAY = 1.0
643
- QUEUE_TYPE = 'memory' # 单机模式
644
- # QUEUE_TYPE = 'redis' # 分布式模式
645
-
646
- # Redis 配置 (分布式模式下使用)
647
- REDIS_HOST = 'localhost'
648
- REDIS_PORT = 6379
649
- REDIS_DB = 0
650
- REDIS_PASSWORD = ''
651
-
652
- # 数据管道配置
653
- # 注意:框架默认管道已自动加载,此处仅用于添加自定义管道
654
- CUSTOM_PIPELINES = [
655
- 'crawlo.pipelines.json_pipeline.JsonPipeline',
656
- 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline', # MySQL存储管道
657
- ]
658
-
659
- # 高级日志配置
660
- LOG_FILE = 'logs/spider.log'
661
- LOG_LEVEL = 'INFO'
662
- LOG_MAX_BYTES = 10 * 1024 * 1024 # 10MB
663
- LOG_BACKUP_COUNT = 5
664
- LOG_JSON_FORMAT = False # 设置为True启用JSON格式
665
-
666
- # 启用高级日志扩展
667
- ADVANCED_LOGGING_ENABLED = True
668
-
669
- # 启用日志监控
670
- LOG_MONITOR_ENABLED = True
671
- LOG_MONITOR_INTERVAL = 30
672
- LOG_MONITOR_DETAILED_STATS = True
673
-
674
- # 添加扩展(注意:框架默认扩展已自动加载,此处仅用于添加自定义扩展)
675
- CUSTOM_EXTENSIONS = [
676
- 'crawlo.extension.memory_monitor.MemoryMonitorExtension',
677
- ]
678
- ```
679
-
680
- ### MySQL 管道配置
681
-
682
- Crawlo 提供了现成的 MySQL 管道实现,可以轻松将爬取的数据存储到 MySQL 数据库中:
683
-
684
- ```
685
- # 在 settings.py 中启用 MySQL 管道
686
- CUSTOM_PIPELINES = [
687
- 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline',
688
- ]
689
-
690
- # MySQL 数据库配置
691
- MYSQL_HOST = 'localhost'
692
- MYSQL_PORT = 3306
693
- MYSQL_USER = 'your_username'
694
- MYSQL_PASSWORD = 'your_password'
695
- MYSQL_DB = 'your_database'
696
- MYSQL_TABLE = 'your_table_name'
697
-
698
- # 可选的批量插入配置
699
- MYSQL_BATCH_SIZE = 100
700
- MYSQL_USE_BATCH = True
701
- ```
702
-
703
- MySQL 管道特性:
704
- - **异步操作**:基于 asyncmy 驱动,提供高性能的异步数据库操作
705
- - **连接池**:自动管理数据库连接,提高效率
706
- - **批量插入**:支持批量插入以提高性能
707
- - **事务支持**:确保数据一致性
708
- - **灵活配置**:支持自定义表名、批量大小等参数
709
-
710
- ### 命令行配置
711
-
712
- ```
713
- # 运行单个爬虫
714
- crawlo run myspider
715
-
716
- # 运行所有爬虫
717
- crawlo run all
718
-
719
- # 在项目子目录中也能正确运行
720
- cd subdirectory
721
- crawlo run myspider
722
- ```
723
-
724
- ---
725
-
726
- <!-- 核心组件 section -->
727
- <h2 align="center">🧩 核心组件</h2>
728
-
729
- ### Request类
730
-
731
- Request类是Crawlo框架中用于封装HTTP请求的核心组件,提供了丰富的功能来处理各种类型的HTTP请求。
732
-
733
- #### 基本用法
734
-
735
- ```python
736
- from crawlo import Request
737
-
738
- # 创建一个基本的GET请求
739
- request = Request('https://example.com')
740
-
741
- # 创建带回调函数的请求
742
- request = Request('https://example.com', callback=self.parse)
743
- ```
744
-
745
- #### params参数(GET请求参数)
746
-
747
- 使用`params`参数来添加GET请求的查询参数,这些参数会自动附加到URL上:
748
-
749
- ```python
750
- # GET请求带参数
751
- request = Request(
752
- url='https://httpbin.org/get',
753
- params={'key1': 'value1', 'key2': 'value2', 'page': 1},
754
- callback=self.parse
755
- )
756
- # 实际请求URL会变成: https://httpbin.org/get?key1=value1&key2=value2&page=1
757
-
758
- # 复杂参数示例
759
- request = Request(
760
- url='https://api.example.com/search',
761
- params={
762
- 'q': 'python爬虫',
763
- 'sort': 'date',
764
- 'order': 'desc',
765
- 'limit': 20
766
- },
767
- callback=self.parse_results
768
- )
769
- ```
770
-
771
- 对于GET请求,如果同时指定了[params](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L55-L55)和[form_data](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L53-L53)参数,它们都会被作为查询参数附加到URL上。
772
-
773
- #### form_data参数(POST表单数据)
774
-
775
- 使用`form_data`参数发送表单数据,会根据请求方法自动处理:
776
-
777
- ```python
778
- # POST请求发送表单数据
779
- request = Request(
780
- url='https://httpbin.org/post',
781
- method='POST',
782
- form_data={
783
- 'username': 'crawlo_user',
784
- 'password': 'secret_password',
785
- 'remember_me': 'true'
786
- },
787
- callback=self.parse_login
788
- )
789
-
790
- # GET请求使用form_data(会自动转换为查询参数)
791
- request = Request(
792
- url='https://httpbin.org/get',
793
- method='GET',
794
- form_data={
795
- 'search': 'crawlo framework',
796
- 'category': 'documentation'
797
- },
798
- callback=self.parse_search
799
- )
800
- ```
801
-
802
- 对于POST请求,[form_data](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L53-L53)会被编码为`application/x-www-form-urlencoded`格式并作为请求体发送。
803
-
804
- #### json_body参数(JSON请求体)
805
-
806
- 使用`json_body`参数发送JSON数据:
807
-
808
- ```python
809
- # 发送JSON数据
810
- request = Request(
811
- url='https://api.example.com/users',
812
- method='POST',
813
- json_body={
814
- 'name': 'Crawlo User',
815
- 'email': 'user@example.com',
816
- 'preferences': {
817
- 'theme': 'dark',
818
- 'notifications': True
819
- }
820
- },
821
- callback=self.parse_response
822
- )
823
-
824
- # PUT请求更新资源
825
- request = Request(
826
- url='https://api.example.com/users/123',
827
- method='PUT',
828
- json_body={
829
- 'name': 'Updated Name',
830
- 'email': 'updated@example.com'
831
- },
832
- callback=self.parse_update
833
- )
834
- ```
835
-
836
- 使用[json_body](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L54-L54)时,会自动设置`Content-Type: application/json`请求头,并将数据序列化为JSON格式。
837
-
838
- #### 混合使用参数
839
-
840
- 可以同时使用多种参数类型,框架会自动处理:
841
-
842
- ```python
843
- # GET请求同时使用params和form_data(都会作为查询参数)
844
- request = Request(
845
- url='https://api.example.com/search',
846
- params={'category': 'books'}, # 作为查询参数
847
- form_data={'q': 'python', 'limit': 10}, # 也作为查询参数
848
- callback=self.parse_search
849
- )
850
-
851
- # POST请求使用form_data和headers
852
- request = Request(
853
- url='https://api.example.com/upload',
854
- method='POST',
855
- form_data={'title': 'My Document'},
856
- headers={'Authorization': 'Bearer token123'},
857
- callback=self.parse_upload
858
- )
859
- ```
860
-
861
- #### 请求配置
862
-
863
- Request类支持丰富的配置选项:
864
-
865
- ```python
866
- request = Request(
867
- url='https://example.com',
868
- method='GET',
869
- headers={'User-Agent': 'Crawlo Bot'},
870
- cookies={'session_id': 'abc123'},
871
- priority=RequestPriority.HIGH,
872
- timeout=30,
873
- proxy='http://proxy.example.com:8080',
874
- dont_filter=True, # 跳过去重检查
875
- meta={'custom_key': 'custom_value'}, # 传递自定义元数据
876
- callback=self.parse
877
- )
878
- ```
879
-
880
- #### 链式调用
881
-
882
- Request类支持链式调用来简化配置:
883
-
884
- ```python
885
- request = Request('https://example.com')\
886
- .add_header('User-Agent', 'Crawlo Bot')\
887
- .set_proxy('http://proxy.example.com:8080')\
888
- .set_timeout(30)\
889
- .add_flag('important')\
890
- .set_meta('custom_key', 'custom_value')
891
- ```
892
-
893
- #### 优先级设置
894
-
895
- Crawlo提供了多种预定义的请求优先级:
896
-
897
- ```python
898
- from crawlo import Request, RequestPriority
899
-
900
- # 设置不同的优先级
901
- urgent_request = Request('https://example.com', priority=RequestPriority.URGENT)
902
- high_request = Request('https://example.com', priority=RequestPriority.HIGH)
903
- normal_request = Request('https://example.com', priority=RequestPriority.NORMAL)
904
- low_request = Request('https://example.com', priority=RequestPriority.LOW)
905
- background_request = Request('https://example.com', priority=RequestPriority.BACKGROUND)
906
- ```
907
-
908
- #### 动态加载器
909
-
910
- 对于需要JavaScript渲染的页面,可以启用动态加载器:
911
-
912
- ```python
913
- # 启用动态加载器
914
- request = Request('https://example.com')\
915
- .set_dynamic_loader(use_dynamic=True)
916
-
917
- # 或者使用链式调用
918
- request = Request('https://example.com')\
919
- .set_dynamic_loader(True, {'wait_time': 3, 'timeout': 30})
920
- ```
921
-
922
- ### 中间件系统
923
- 灵活的中间件系统,支持请求预处理、响应处理和异常处理。
924
-
925
- Crawlo框架内置了多种中间件,其中代理中间件有两种实现:
926
-
927
- 1. **ProxyMiddleware(复杂版)**:
928
- - 动态从API获取代理
929
- - 代理池管理
930
- - 健康检查和成功率统计
931
- - 复杂的代理提取逻辑
932
- - 适用于需要高级代理管理功能的场景
933
-
934
- 2. **SimpleProxyMiddleware(简化版)**:
935
- - 基于固定代理列表的简单实现
936
- - 轻量级,代码简洁
937
- - 易于配置和使用
938
- - 适用于只需要基本代理功能的场景
939
-
940
- 如果需要使用简化版代理中间件,可以在配置文件中替换默认的代理中间件:
941
-
942
- ``python
943
- # settings.py
944
- MIDDLEWARES = [
945
- # 注释掉复杂版代理中间件
946
- # 'crawlo.middleware.proxy.ProxyMiddleware',
947
- # 启用简化版代理中间件
948
- 'crawlo.middleware.simple_proxy.SimpleProxyMiddleware',
949
- ]
950
-
951
- # 配置代理列表
952
- PROXY_ENABLED = True
953
- PROXY_LIST = [
954
- "http://proxy1.example.com:8080",
955
- "http://proxy2.example.com:8080",
956
- ]
957
- ```
958
-
959
- 有关代理中间件的详细使用说明,请参考[代理中间件示例项目](examples/simple_proxy_example/)。
960
-
961
- ### 管道系统
962
- 可扩展的数据处理管道,支持多种存储方式(控制台、数据库等)和去重功能:
963
- - **ConsolePipeline**: 控制台输出管道
964
- - **JsonPipeline**: JSON文件存储管道
965
- - **RedisDedupPipeline**: Redis去重管道,基于Redis集合实现分布式去重
966
- - **AsyncmyMySQLPipeline**: MySQL数据库存储管道,基于asyncmy驱动
967
-
968
- ### 扩展组件
969
- 功能增强扩展,包括日志、监控、性能分析等:
970
- - **LogIntervalExtension**: 定时日志扩展
971
- - **LogStats**: 统计日志扩展
972
- - **CustomLoggerExtension**: 自定义日志扩展
973
- - **MemoryMonitorExtension**: 内存监控扩展(监控爬虫进程内存使用情况)
974
- - **PerformanceProfilerExtension**: 性能分析扩展
975
- - **HealthCheckExtension**: 健康检查扩展
976
- - **RequestRecorderExtension**: 请求记录扩展
977
-
978
- ### 过滤系统
979
- 智能去重过滤,支持多种去重策略(内存、Redis、Bloom Filter)。
980
-
981
- ---
982
-
983
- <!-- 示例项目 section -->
984
- <h2 align="center">📦 示例项目</h2>
985
-
986
- - [OFweek分布式爬虫](examples/ofweek_distributed/) - 复杂的分布式爬虫示例,包含Redis去重功能
987
- - [OFweek独立爬虫](examples/ofweek_standalone/) - 独立运行的爬虫示例
988
- - [OFweek混合模式爬虫](examples/ofweek_spider/) - 支持单机和分布式模式切换的爬虫示例
989
-
990
- ---
991
-
992
- <!-- 文档 section -->
993
- <h2 align="center">📚 文档</h2>
994
-
995
- 完整的文档请访问 [Crawlo Documentation](https://crawlo.readthedocs.io/)
996
-
997
- - [快速开始指南](docs/modules/index.md)
998
- - [模块化文档](docs/modules/index.md)
999
- - [核心引擎文档](docs/modules/core/engine.md)
1000
- - [调度器文档](docs/modules/core/scheduler.md)
1001
- - [下载器文档](docs/modules/downloader/index.md)
1002
- - [中间件文档](docs/modules/middleware/index.md)
1003
- - [管道文档](docs/modules/pipeline/index.md)
1004
- - [队列文档](docs/modules/queue/index.md)
1005
- - [过滤器文档](docs/modules/filter/index.md)
1006
- - [扩展组件文档](docs/modules/extension/index.md)
1007
-
1008
- ---
1009
-
1010
- <!-- 贡献 section -->
1011
- <h2 align="center">🤝 贡献</h2>
1012
-
1013
- 欢迎提交 Issue 和 Pull Request 来帮助改进 Crawlo!
1014
-
1015
- ---
1016
-
1017
- <!-- 许可证 section -->
1018
- <h2 align="center">📄 许可证</h2>
1019
-
1020
- 本项目采用 MIT 许可证,详情请见 [LICENSE](LICENSE) 文件。
1
+ Metadata-Version: 2.4
2
+ Name: crawlo
3
+ Version: 1.3.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: curl-cffi>=0.13.0
22
+ Requires-Dist: lxml>=5.2.1
23
+ Requires-Dist: motor>=3.7.0
24
+ Requires-Dist: parsel>=1.9.1
25
+ Requires-Dist: pydantic>=2.11.7
26
+ Requires-Dist: pymongo>=4.11
27
+ Requires-Dist: PyMySQL>=1.1.1
28
+ Requires-Dist: python-dateutil>=2.9.0.post0
29
+ Requires-Dist: redis>=6.2.0
30
+ Requires-Dist: requests>=2.32.4
31
+ Requires-Dist: six>=1.17.0
32
+ Requires-Dist: ujson>=5.9.0
33
+ Requires-Dist: urllib3>=2.5.0
34
+ Requires-Dist: w3lib>=2.1.2
35
+ Requires-Dist: rich>=14.1.0
36
+ Requires-Dist: astor>=0.8.1
37
+ Requires-Dist: watchdog>=6.0.0
38
+ Provides-Extra: render
39
+ Requires-Dist: webdriver-manager>=4.0.0; extra == "render"
40
+ Requires-Dist: playwright; extra == "render"
41
+ Requires-Dist: selenium>=3.141.0; extra == "render"
42
+ Provides-Extra: all
43
+ Requires-Dist: bitarray>=1.5.3; extra == "all"
44
+ Requires-Dist: PyExecJS>=1.5.1; extra == "all"
45
+ Requires-Dist: pymongo>=3.10.1; extra == "all"
46
+ Requires-Dist: redis-py-cluster>=2.1.0; extra == "all"
47
+ Requires-Dist: webdriver-manager>=4.0.0; extra == "all"
48
+ Requires-Dist: playwright; extra == "all"
49
+ Requires-Dist: selenium>=3.141.0; extra == "all"
50
+
51
+ <!-- markdownlint-disable MD033 MD041 -->
52
+ <div align="center">
53
+ <h1 align="center">Crawlo</h1>
54
+ <p align="center">异步分布式爬虫框架</p>
55
+ <p align="center"><strong>基于 asyncio 的高性能异步分布式爬虫框架,支持单机和分布式部署</strong></p>
56
+
57
+ <p align="center">
58
+ <a href="https://www.python.org/downloads/">
59
+ <img src="https://img.shields.io/badge/python-%3C%3D3.12-blue" alt="Python Version">
60
+ </a>
61
+ <a href="LICENSE">
62
+ <img src="https://img.shields.io/badge/license-MIT-green" alt="License">
63
+ </a>
64
+ <a href="https://crawlo.readthedocs.io/">
65
+ <img src="https://img.shields.io/badge/docs-latest-brightgreen" alt="Documentation">
66
+ </a>
67
+ <a href="https://github.com/crawlo/crawlo/actions">
68
+ <img src="https://github.com/crawlo/crawlo/workflows/CI/badge.svg" alt="CI Status">
69
+ </a>
70
+ </p>
71
+
72
+ <p align="center">
73
+ <a href="#-特性">特性</a> •
74
+ <a href="#-快速开始">快速开始</a> •
75
+ <a href="#-命令行工具">命令行工具</a> •
76
+ <a href="#-示例项目">示例项目</a>
77
+ </p>
78
+ </div>
79
+
80
+ <br />
81
+
82
+ <!-- 特性 section -->
83
+ <div align="center">
84
+ <h2>🌟 特性</h2>
85
+
86
+ <table>
87
+ <thead>
88
+ <tr>
89
+ <th>特性</th>
90
+ <th>描述</th>
91
+ </tr>
92
+ </thead>
93
+ <tbody>
94
+ <tr>
95
+ <td>⚡ <strong>异步高性能</strong></td>
96
+ <td>基于 asyncio 实现,充分利用现代 CPU 夯性能</td>
97
+ </tr>
98
+ <tr>
99
+ <td>🌐 <strong>分布式支持</strong></td>
100
+ <td>内置 Redis 队列,轻松实现分布式部署</td>
101
+ </tr>
102
+ <tr>
103
+ <td>🔧 <strong>模块化设计</strong></td>
104
+ <td>中间件、管道、扩展组件系统,易于定制和扩展</td>
105
+ </tr>
106
+ <tr>
107
+ <td>🔄 <strong>智能去重</strong></td>
108
+ <td>多种去重策略(内存、Redis、Bloom Filter)</td>
109
+ </tr>
110
+ <tr>
111
+ <td>⚙️ <strong>灵活配置</strong></td>
112
+ <td>支持多种配置方式,适应不同场景需求</td>
113
+ </tr>
114
+ <tr>
115
+ <td>📋 <strong>高级日志</strong></td>
116
+ <td>支持日志轮转、结构化日志、JSON格式等高级功能</td>
117
+ </tr>
118
+ <tr>
119
+ <td>📚 <strong>丰富文档</strong></td>
120
+ <td>完整的中英文双语文档和示例项目</td>
121
+ </tr>
122
+ </tbody>
123
+ </table>
124
+ </div>
125
+
126
+ <br />
127
+
128
+ ---
129
+
130
+ <!-- 快速开始 section -->
131
+ <h2 align="center">🚀 快速开始</h2>
132
+
133
+ ### 安装
134
+
135
+ ```bash
136
+ pip install crawlo
137
+ ```
138
+
139
+ ### 创建项目
140
+
141
+ ```bash
142
+ # 创建默认项目
143
+ crawlo startproject myproject
144
+
145
+ # 创建分布式模板项目
146
+ crawlo startproject myproject distributed
147
+
148
+ # 创建项目并选择特定模块
149
+ crawlo startproject myproject --modules mysql,redis,proxy
150
+
151
+ cd myproject
152
+ ```
153
+
154
+ ### 生成爬虫
155
+
156
+ ```bash
157
+ # 在项目目录中生成爬虫
158
+ crawlo genspider news_spider news.example.com
159
+ ```
160
+
161
+ ### 编写爬虫
162
+
163
+ ``python
164
+ from crawlo import Spider, Request, Item
165
+
166
+ class MyItem(Item):
167
+ title = ''
168
+ url = ''
169
+
170
+ class MySpider(Spider):
171
+ name = 'myspider'
172
+
173
+ async def start_requests(self):
174
+ yield Request('https://httpbin.org/get', callback=self.parse)
175
+
176
+ async def parse(self, response):
177
+ yield MyItem(
178
+ title='Example Title',
179
+ url=response.url
180
+ )
181
+ ```
182
+
183
+ ### 运行爬虫
184
+
185
+ ```bash
186
+ # 使用命令行工具运行爬虫(推荐)
187
+ crawlo run myspider
188
+
189
+ # 使用项目自带的 run.py 脚本运行
190
+ python run.py
191
+
192
+ # 运行所有爬虫
193
+ crawlo run all
194
+
195
+ # 在项目子目录中也能正确运行
196
+ cd subdirectory
197
+ crawlo run myspider
198
+ ```
199
+
200
+ ---
201
+
202
+ <!-- 命令行工具 section -->
203
+ <h2 align="center">🔧 命令行工具</h2>
204
+
205
+ Crawlo 提供了丰富的命令行工具,简化项目创建和管理。
206
+
207
+ ### crawlo startproject
208
+
209
+ 创建新的爬虫项目。
210
+
211
+ ```bash
212
+ # 创建默认项目
213
+ crawlo startproject myproject
214
+
215
+ # 创建指定模板的项目
216
+ crawlo startproject myproject simple
217
+ crawlo startproject myproject distributed
218
+ ```
219
+
220
+ ### crawlo genspider
221
+
222
+ 在现有项目中生成新的爬虫。
223
+
224
+ ```bash
225
+ # 在当前目录生成爬虫
226
+ crawlo genspider myspider http://example.com
227
+
228
+ # 指定模板生成爬虫
229
+ crawlo genspider myspider http://example.com --template basic
230
+ ```
231
+
232
+ ### crawlo run
233
+
234
+ 运行指定的爬虫。
235
+
236
+ ```bash
237
+ # 运行单个爬虫
238
+ crawlo run myspider
239
+
240
+ # 运行所有爬虫
241
+ crawlo run all
242
+
243
+ # 以JSON格式输出结果
244
+ crawlo run myspider --json
245
+
246
+ # 禁用统计信息
247
+ crawlo run myspider --no-stats
248
+ ```
249
+
250
+ ### crawlo list
251
+
252
+ 列出项目中的所有爬虫。
253
+
254
+ ```bash
255
+ crawlo list
256
+ ```
257
+
258
+ ### crawlo check
259
+
260
+ 检查项目配置和爬虫实现。
261
+
262
+ ```bash
263
+ # 检查所有爬虫
264
+ crawlo check
265
+
266
+ # 检查特定爬虫
267
+ crawlo check myspider
268
+ ```
269
+
270
+ ### crawlo stats
271
+
272
+ 查看爬虫统计信息。
273
+
274
+ ```bash
275
+ # 查看统计信息
276
+ crawlo stats
277
+ ```
278
+
279
+ ---
280
+
281
+ <!-- 配置方式 section -->
282
+ <h2 align="center">⚙️ 配置方式</h2>
283
+
284
+ Crawlo 提供了多种灵活的配置方式,以适应不同的使用场景和开发需求。
285
+
286
+ ### 三种配置方式详解
287
+
288
+ #### 1. 配置工厂方式(推荐)
289
+
290
+ 使用 `CrawloConfig` 配置工厂是推荐的配置方式,它提供了类型安全和智能提示。
291
+
292
+ ```python
293
+ from crawlo.config import CrawloConfig
294
+ from crawlo.crawler import CrawlerProcess
295
+
296
+ # 单机模式配置
297
+ config = CrawloConfig.standalone(
298
+ concurrency=8,
299
+ download_delay=1.0
300
+ )
301
+
302
+ # 分布式模式配置
303
+ config = CrawloConfig.distributed(
304
+ redis_host='127.0.0.1',
305
+ redis_port=6379,
306
+ project_name='myproject',
307
+ concurrency=16
308
+ )
309
+
310
+ # 自动检测模式配置
311
+ config = CrawloConfig.auto(concurrency=12)
312
+
313
+ # 从环境变量读取配置
314
+ config = CrawloConfig.from_env()
315
+
316
+ # 创建爬虫进程
317
+ process = CrawlerProcess(settings=config.to_dict())
318
+ ```
319
+
320
+ #### 2. 直接配置方式
321
+
322
+ 直接在 `settings.py` 文件中配置各项参数,适合需要精细控制的场景。
323
+
324
+ ```
325
+ # settings.py
326
+ PROJECT_NAME = 'myproject'
327
+ RUN_MODE = 'standalone' # 或 'distributed' 或 'auto'
328
+ CONCURRENCY = 8
329
+ DOWNLOAD_DELAY = 1.0
330
+
331
+ # 分布式模式下需要配置Redis
332
+ REDIS_HOST = '127.0.0.1'
333
+ REDIS_PORT = 6379
334
+ REDIS_PASSWORD = ''
335
+
336
+ # 其他配置...
337
+ ```
338
+
339
+ #### 3. 环境变量方式
340
+
341
+ 通过环境变量配置,适合部署和CI/CD场景。
342
+
343
+ ```bash
344
+ # 设置环境变量
345
+ export CRAWLO_MODE=standalone
346
+ export CONCURRENCY=8
347
+ export DOWNLOAD_DELAY=1.0
348
+ export REDIS_HOST=127.0.0.1
349
+ export REDIS_PORT=6379
350
+ ```
351
+
352
+ ```python
353
+ # 在代码中读取环境变量
354
+ from crawlo.config import CrawloConfig
355
+ config = CrawloConfig.from_env()
356
+ process = CrawlerProcess(settings=config.to_dict())
357
+ ```
358
+
359
+ ### 不同运行模式下的最佳配置方式
360
+
361
+ #### 单机模式 (standalone)
362
+
363
+ 适用于开发调试、小规模数据采集、个人项目。
364
+
365
+ **推荐配置方式:**
366
+ ```python
367
+ from crawlo.config import CrawloConfig
368
+ config = CrawloConfig.standalone(concurrency=4, download_delay=1.0)
369
+ process = CrawlerProcess(settings=config.to_dict())
370
+ ```
371
+
372
+ **特点:**
373
+ - 简单易用,资源占用少
374
+ - 无需额外依赖(如Redis)
375
+ - 适合个人开发环境
376
+
377
+ #### 分布式模式 (distributed)
378
+
379
+ 适用于大规模数据采集、多节点协同工作、高并发需求。
380
+
381
+ **推荐配置方式:**
382
+ ```python
383
+ from crawlo.config import CrawloConfig
384
+ config = CrawloConfig.distributed(
385
+ redis_host='your_redis_host',
386
+ redis_port=6379,
387
+ project_name='myproject',
388
+ concurrency=16
389
+ )
390
+ process = CrawlerProcess(settings=config.to_dict())
391
+ ```
392
+
393
+ **特点:**
394
+ - 支持多节点扩展
395
+ - 高并发处理能力
396
+ - 需要Redis支持
397
+
398
+ #### 自动检测模式 (auto)
399
+
400
+ 适用于希望根据环境自动选择最佳运行方式。
401
+
402
+ **推荐配置方式:**
403
+ ```python
404
+ from crawlo.config import CrawloConfig
405
+ config = CrawloConfig.auto(concurrency=12)
406
+ process = CrawlerProcess(settings=config.to_dict())
407
+ ```
408
+
409
+ **特点:**
410
+ - 智能检测环境配置
411
+ - 自动选择运行模式
412
+ - 适合在不同环境中使用同一套配置
413
+
414
+ ### 组件配置说明
415
+
416
+ Crawlo框架的中间件、管道和扩展组件采用模块化设计,框架会自动加载默认组件,用户只需配置自定义组件。
417
+
418
+ #### 中间件配置
419
+
420
+ 框架默认加载以下中间件:
421
+ - RequestIgnoreMiddleware:忽略无效请求
422
+ - DownloadDelayMiddleware:控制请求频率
423
+ - DefaultHeaderMiddleware:添加默认请求头
424
+ - ProxyMiddleware:设置代理
425
+ - OffsiteMiddleware:站外请求过滤
426
+ - RetryMiddleware:失败请求重试
427
+ - ResponseCodeMiddleware:处理特殊状态码
428
+ - ResponseFilterMiddleware:响应内容过滤
429
+
430
+ 用户可以通过`CUSTOM_MIDDLEWARES`配置自定义中间件:
431
+
432
+ ``python
433
+ # settings.py
434
+ CUSTOM_MIDDLEWARES = [
435
+ 'myproject.middlewares.CustomMiddleware',
436
+ ]
437
+ ```
438
+
439
+ > **注意**:DefaultHeaderMiddleware 和 OffsiteMiddleware 需要相应的配置才能启用:
440
+ > - DefaultHeaderMiddleware 需要配置 `DEFAULT_REQUEST_HEADERS` 或 `USER_AGENT` 参数
441
+ > - OffsiteMiddleware 需要配置 `ALLOWED_DOMAINS` 参数
442
+ >
443
+ > 如果未配置相应参数,这些中间件会因为 NotConfiguredError 而被禁用。
444
+
445
+ > **注意**:中间件的顺序很重要。SimpleProxyMiddleware 通常放在列表末尾,
446
+ > 这样可以在所有默认中间件处理后再应用代理设置。
447
+
448
+ #### 管道配置
449
+
450
+ 框架默认加载以下管道:
451
+ - ConsolePipeline:控制台输出
452
+ - 默认去重管道(根据运行模式自动选择)
453
+
454
+ 用户可以通过`CUSTOM_PIPELINES`配置自定义管道:
455
+
456
+ ```python
457
+ # settings.py
458
+ CUSTOM_PIPELINES = [
459
+ 'crawlo.pipelines.json_pipeline.JsonPipeline',
460
+ 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline',
461
+ ]
462
+ ```
463
+
464
+ #### 扩展配置
465
+
466
+ 框架默认加载以下扩展:
467
+ - LogIntervalExtension:定时日志
468
+ - LogStats:统计信息
469
+ - CustomLoggerExtension:自定义日志
470
+
471
+ 用户可以通过`CUSTOM_EXTENSIONS`配置自定义扩展:
472
+
473
+ ```python
474
+ # settings.py
475
+ CUSTOM_EXTENSIONS = [
476
+ 'crawlo.extension.memory_monitor.MemoryMonitorExtension',
477
+ ]
478
+ ```
479
+
480
+ <!-- 架构设计 section -->
481
+ <h2 align="center">🏗️ 架构设计</h2>
482
+
483
+ ### 核心组件说明
484
+
485
+ Crawlo 框架由以下核心组件构成:
486
+
487
+ <table>
488
+ <thead>
489
+ <tr>
490
+ <th>组件</th>
491
+ <th>功能描述</th>
492
+ </tr>
493
+ </thead>
494
+ <tbody>
495
+ <tr>
496
+ <td><strong>Crawler</strong></td>
497
+ <td>爬虫运行实例,管理Spider与引擎的生命周期</td>
498
+ </tr>
499
+ <tr>
500
+ <td><strong>Engine</strong></td>
501
+ <td>引擎组件,协调Scheduler、Downloader、Processor</td>
502
+ </tr>
503
+ <tr>
504
+ <td><strong>Scheduler</strong></td>
505
+ <td>调度器,管理请求队列和去重过滤</td>
506
+ </tr>
507
+ <tr>
508
+ <td><strong>Downloader</strong></td>
509
+ <td>下载器,负责网络请求,支持多种实现(aiohttp, httpx, curl-cffi)</td>
510
+ </tr>
511
+ <tr>
512
+ <td><strong>Processor</strong></td>
513
+ <td>处理器,处理响应数据和管道</td>
514
+ </tr>
515
+ <tr>
516
+ <td><strong>QueueManager</strong></td>
517
+ <td>统一的队列管理器,支持内存队列和Redis队列的自动切换</td>
518
+ </tr>
519
+ <tr>
520
+ <td><strong>Filter</strong></td>
521
+ <td>请求去重过滤器,支持内存和Redis两种实现</td>
522
+ </tr>
523
+ <tr>
524
+ <td><strong>Middleware</strong></td>
525
+ <td>中间件系统,处理请求/响应的预处理和后处理</td>
526
+ </tr>
527
+ <tr>
528
+ <td><strong>Pipeline</strong></td>
529
+ <td>数据处理管道,支持多种存储方式(控制台、数据库等)和去重功能</td>
530
+ </tr>
531
+ <tr>
532
+ <td><strong>Spider</strong></td>
533
+ <td>爬虫基类,定义爬取逻辑</td>
534
+ </tr>
535
+ </tbody>
536
+ </table>
537
+
538
+ ### 运行模式
539
+
540
+ Crawlo支持三种运行模式:
541
+
542
+ <table>
543
+ <thead>
544
+ <tr>
545
+ <th>模式</th>
546
+ <th>描述</th>
547
+ <th>队列类型</th>
548
+ <th>过滤器类型</th>
549
+ </tr>
550
+ </thead>
551
+ <tbody>
552
+ <tr>
553
+ <td><strong>standalone</strong></td>
554
+ <td>单机模式</td>
555
+ <td>内存队列</td>
556
+ <td>内存过滤器</td>
557
+ </tr>
558
+ <tr>
559
+ <td><strong>distributed</strong></td>
560
+ <td>分布式模式</td>
561
+ <td>Redis队列</td>
562
+ <td>Redis过滤器</td>
563
+ </tr>
564
+ <tr>
565
+ <td><strong>auto</strong></td>
566
+ <td>自动检测模式</td>
567
+ <td>根据环境自动选择最佳运行方式</td>
568
+ <td>根据环境自动选择</td>
569
+ </tr>
570
+ </tbody>
571
+ </table>
572
+
573
+ > **运行模式说明**: distributed模式为多节点分布式设计,强制使用Redis队列和去重;standalone+auto为单机智能模式,根据环境自动选择内存或Redis队列与去重策略,零配置启动。
574
+
575
+ #### 运行模式选择指南
576
+
577
+ ##### 1. 单机模式 (standalone)
578
+ - **适用场景**:
579
+ - 开发和测试阶段
580
+ - 小规模数据采集(几千到几万条数据)
581
+ - 学习和演示用途
582
+ - 对目标网站负载要求不高的场景
583
+ - **优势**:
584
+ - 配置简单,无需额外依赖
585
+ - 资源消耗低
586
+ - 启动快速
587
+ - 适合本地开发调试
588
+ - **限制**:
589
+ - 无法跨会话去重
590
+ - 无法分布式部署
591
+ - 内存占用随数据量增长
592
+
593
+ ##### 2. 分布式模式 (distributed)
594
+ - **适用场景**:
595
+ - 大规模数据采集(百万级以上)
596
+ - 需要多节点协同工作
597
+ - 要求跨会话、跨节点去重
598
+ - 生产环境部署
599
+ - **优势**:
600
+ - 支持水平扩展
601
+ - 跨节点任务协调
602
+ - 持久化去重过滤
603
+ - 高可用性
604
+ - **要求**:
605
+ - 需要Redis服务器
606
+ - 网络环境稳定
607
+ - 更复杂的配置管理
608
+
609
+ ##### 3. 自动模式 (auto)
610
+ - **适用场景**:
611
+ - 希望根据环境自动选择最佳配置
612
+ - 开发和生产环境使用同一套代码
613
+ - 动态适应运行环境
614
+ - **工作机制**:
615
+ - 检测Redis可用性
616
+ - Redis可用时自动切换到分布式模式
617
+ - Redis不可用时回退到单机模式
618
+ - **优势**:
619
+ - 环境适应性强
620
+ - 部署灵活
621
+ - 开发和生产环境配置统一
622
+
623
+ #### 队列类型选择指南
624
+
625
+ Crawlo支持三种队列类型,可通过`QUEUE_TYPE`配置项设置:
626
+
627
+ - **memory**:使用内存队列,适用于单机模式
628
+ - **redis**:使用Redis队列,适用于分布式模式
629
+ - **auto**:自动检测模式,根据Redis可用性自动选择
630
+
631
+ 推荐使用`auto`模式,让框架根据环境自动选择最适合的队列类型。
632
+
633
+ <!-- 配置系统 section -->
634
+ <h2 align="center">🎛️ 配置系统</h2>
635
+
636
+ ### 传统配置方式
637
+
638
+ ```
639
+ # settings.py
640
+ PROJECT_NAME = 'myproject'
641
+ CONCURRENCY = 16
642
+ DOWNLOAD_DELAY = 1.0
643
+ QUEUE_TYPE = 'memory' # 单机模式
644
+ # QUEUE_TYPE = 'redis' # 分布式模式
645
+
646
+ # Redis 配置 (分布式模式下使用)
647
+ REDIS_HOST = 'localhost'
648
+ REDIS_PORT = 6379
649
+ REDIS_DB = 0
650
+ REDIS_PASSWORD = ''
651
+
652
+ # 数据管道配置
653
+ # 注意:框架默认管道已自动加载,此处仅用于添加自定义管道
654
+ CUSTOM_PIPELINES = [
655
+ 'crawlo.pipelines.json_pipeline.JsonPipeline',
656
+ 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline', # MySQL存储管道
657
+ ]
658
+
659
+ # 高级日志配置
660
+ LOG_FILE = 'logs/spider.log'
661
+ LOG_LEVEL = 'INFO'
662
+ LOG_MAX_BYTES = 10 * 1024 * 1024 # 10MB
663
+ LOG_BACKUP_COUNT = 5
664
+ LOG_JSON_FORMAT = False # 设置为True启用JSON格式
665
+
666
+ # 启用高级日志扩展
667
+ ADVANCED_LOGGING_ENABLED = True
668
+
669
+ # 启用日志监控
670
+ LOG_MONITOR_ENABLED = True
671
+ LOG_MONITOR_INTERVAL = 30
672
+ LOG_MONITOR_DETAILED_STATS = True
673
+
674
+ # 添加扩展(注意:框架默认扩展已自动加载,此处仅用于添加自定义扩展)
675
+ CUSTOM_EXTENSIONS = [
676
+ 'crawlo.extension.memory_monitor.MemoryMonitorExtension',
677
+ ]
678
+ ```
679
+
680
+ ### MySQL 管道配置
681
+
682
+ Crawlo 提供了现成的 MySQL 管道实现,可以轻松将爬取的数据存储到 MySQL 数据库中:
683
+
684
+ ```
685
+ # 在 settings.py 中启用 MySQL 管道
686
+ CUSTOM_PIPELINES = [
687
+ 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline',
688
+ ]
689
+
690
+ # MySQL 数据库配置
691
+ MYSQL_HOST = 'localhost'
692
+ MYSQL_PORT = 3306
693
+ MYSQL_USER = 'your_username'
694
+ MYSQL_PASSWORD = 'your_password'
695
+ MYSQL_DB = 'your_database'
696
+ MYSQL_TABLE = 'your_table_name'
697
+
698
+ # 可选的批量插入配置
699
+ MYSQL_BATCH_SIZE = 100
700
+ MYSQL_USE_BATCH = True
701
+ ```
702
+
703
+ MySQL 管道特性:
704
+ - **异步操作**:基于 asyncmy 驱动,提供高性能的异步数据库操作
705
+ - **连接池**:自动管理数据库连接,提高效率
706
+ - **批量插入**:支持批量插入以提高性能
707
+ - **事务支持**:确保数据一致性
708
+ - **灵活配置**:支持自定义表名、批量大小等参数
709
+
710
+ ### 命令行配置
711
+
712
+ ```
713
+ # 运行单个爬虫
714
+ crawlo run myspider
715
+
716
+ # 运行所有爬虫
717
+ crawlo run all
718
+
719
+ # 在项目子目录中也能正确运行
720
+ cd subdirectory
721
+ crawlo run myspider
722
+ ```
723
+
724
+ ---
725
+
726
+ <!-- 核心组件 section -->
727
+ <h2 align="center">🧩 核心组件</h2>
728
+
729
+ ### Request类
730
+
731
+ Request类是Crawlo框架中用于封装HTTP请求的核心组件,提供了丰富的功能来处理各种类型的HTTP请求。
732
+
733
+ #### 基本用法
734
+
735
+ ```python
736
+ from crawlo import Request
737
+
738
+ # 创建一个基本的GET请求
739
+ request = Request('https://example.com')
740
+
741
+ # 创建带回调函数的请求
742
+ request = Request('https://example.com', callback=self.parse)
743
+ ```
744
+
745
+ #### params参数(GET请求参数)
746
+
747
+ 使用`params`参数来添加GET请求的查询参数,这些参数会自动附加到URL上:
748
+
749
+ ```python
750
+ # GET请求带参数
751
+ request = Request(
752
+ url='https://httpbin.org/get',
753
+ params={'key1': 'value1', 'key2': 'value2', 'page': 1},
754
+ callback=self.parse
755
+ )
756
+ # 实际请求URL会变成: https://httpbin.org/get?key1=value1&key2=value2&page=1
757
+
758
+ # 复杂参数示例
759
+ request = Request(
760
+ url='https://api.example.com/search',
761
+ params={
762
+ 'q': 'python爬虫',
763
+ 'sort': 'date',
764
+ 'order': 'desc',
765
+ 'limit': 20
766
+ },
767
+ callback=self.parse_results
768
+ )
769
+ ```
770
+
771
+ 对于GET请求,如果同时指定了[params](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L55-L55)和[form_data](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L53-L53)参数,它们都会被作为查询参数附加到URL上。
772
+
773
+ #### form_data参数(POST表单数据)
774
+
775
+ 使用`form_data`参数发送表单数据,会根据请求方法自动处理:
776
+
777
+ ```python
778
+ # POST请求发送表单数据
779
+ request = Request(
780
+ url='https://httpbin.org/post',
781
+ method='POST',
782
+ form_data={
783
+ 'username': 'crawlo_user',
784
+ 'password': 'secret_password',
785
+ 'remember_me': 'true'
786
+ },
787
+ callback=self.parse_login
788
+ )
789
+
790
+ # GET请求使用form_data(会自动转换为查询参数)
791
+ request = Request(
792
+ url='https://httpbin.org/get',
793
+ method='GET',
794
+ form_data={
795
+ 'search': 'crawlo framework',
796
+ 'category': 'documentation'
797
+ },
798
+ callback=self.parse_search
799
+ )
800
+ ```
801
+
802
+ 对于POST请求,[form_data](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L53-L53)会被编码为`application/x-www-form-urlencoded`格式并作为请求体发送。
803
+
804
+ #### json_body参数(JSON请求体)
805
+
806
+ 使用`json_body`参数发送JSON数据:
807
+
808
+ ```python
809
+ # 发送JSON数据
810
+ request = Request(
811
+ url='https://api.example.com/users',
812
+ method='POST',
813
+ json_body={
814
+ 'name': 'Crawlo User',
815
+ 'email': 'user@example.com',
816
+ 'preferences': {
817
+ 'theme': 'dark',
818
+ 'notifications': True
819
+ }
820
+ },
821
+ callback=self.parse_response
822
+ )
823
+
824
+ # PUT请求更新资源
825
+ request = Request(
826
+ url='https://api.example.com/users/123',
827
+ method='PUT',
828
+ json_body={
829
+ 'name': 'Updated Name',
830
+ 'email': 'updated@example.com'
831
+ },
832
+ callback=self.parse_update
833
+ )
834
+ ```
835
+
836
+ 使用[json_body](file:///Users/oscar/projects/Crawlo/crawlo/network/request.py#L54-L54)时,会自动设置`Content-Type: application/json`请求头,并将数据序列化为JSON格式。
837
+
838
+ #### 混合使用参数
839
+
840
+ 可以同时使用多种参数类型,框架会自动处理:
841
+
842
+ ```python
843
+ # GET请求同时使用params和form_data(都会作为查询参数)
844
+ request = Request(
845
+ url='https://api.example.com/search',
846
+ params={'category': 'books'}, # 作为查询参数
847
+ form_data={'q': 'python', 'limit': 10}, # 也作为查询参数
848
+ callback=self.parse_search
849
+ )
850
+
851
+ # POST请求使用form_data和headers
852
+ request = Request(
853
+ url='https://api.example.com/upload',
854
+ method='POST',
855
+ form_data={'title': 'My Document'},
856
+ headers={'Authorization': 'Bearer token123'},
857
+ callback=self.parse_upload
858
+ )
859
+ ```
860
+
861
+ #### 请求配置
862
+
863
+ Request类支持丰富的配置选项:
864
+
865
+ ```python
866
+ request = Request(
867
+ url='https://example.com',
868
+ method='GET',
869
+ headers={'User-Agent': 'Crawlo Bot'},
870
+ cookies={'session_id': 'abc123'},
871
+ priority=RequestPriority.HIGH,
872
+ timeout=30,
873
+ proxy='http://proxy.example.com:8080',
874
+ dont_filter=True, # 跳过去重检查
875
+ meta={'custom_key': 'custom_value'}, # 传递自定义元数据
876
+ callback=self.parse
877
+ )
878
+ ```
879
+
880
+ #### 链式调用
881
+
882
+ Request类支持链式调用来简化配置:
883
+
884
+ ```python
885
+ request = Request('https://example.com')\
886
+ .add_header('User-Agent', 'Crawlo Bot')\
887
+ .set_proxy('http://proxy.example.com:8080')\
888
+ .set_timeout(30)\
889
+ .add_flag('important')\
890
+ .set_meta('custom_key', 'custom_value')
891
+ ```
892
+
893
+ #### 优先级设置
894
+
895
+ Crawlo提供了多种预定义的请求优先级:
896
+
897
+ ```python
898
+ from crawlo import Request, RequestPriority
899
+
900
+ # 设置不同的优先级
901
+ urgent_request = Request('https://example.com', priority=RequestPriority.URGENT)
902
+ high_request = Request('https://example.com', priority=RequestPriority.HIGH)
903
+ normal_request = Request('https://example.com', priority=RequestPriority.NORMAL)
904
+ low_request = Request('https://example.com', priority=RequestPriority.LOW)
905
+ background_request = Request('https://example.com', priority=RequestPriority.BACKGROUND)
906
+ ```
907
+
908
+ #### 动态加载器
909
+
910
+ 对于需要JavaScript渲染的页面,可以启用动态加载器:
911
+
912
+ ```python
913
+ # 启用动态加载器
914
+ request = Request('https://example.com')\
915
+ .set_dynamic_loader(use_dynamic=True)
916
+
917
+ # 或者使用链式调用
918
+ request = Request('https://example.com')\
919
+ .set_dynamic_loader(True, {'wait_time': 3, 'timeout': 30})
920
+ ```
921
+
922
+ ### 中间件系统
923
+ 灵活的中间件系统,支持请求预处理、响应处理和异常处理。
924
+
925
+ Crawlo框架内置了多种中间件,其中代理中间件有两种实现:
926
+
927
+ 1. **ProxyMiddleware(复杂版)**:
928
+ - 动态从API获取代理
929
+ - 代理池管理
930
+ - 健康检查和成功率统计
931
+ - 复杂的代理提取逻辑
932
+ - 适用于需要高级代理管理功能的场景
933
+
934
+ 2. **SimpleProxyMiddleware(简化版)**:
935
+ - 基于固定代理列表的简单实现
936
+ - 轻量级,代码简洁
937
+ - 易于配置和使用
938
+ - 适用于只需要基本代理功能的场景
939
+
940
+ 如果需要使用简化版代理中间件,可以在配置文件中替换默认的代理中间件:
941
+
942
+ ``python
943
+ # settings.py
944
+ MIDDLEWARES = [
945
+ # 注释掉复杂版代理中间件
946
+ # 'crawlo.middleware.proxy.ProxyMiddleware',
947
+ # 启用简化版代理中间件
948
+ 'crawlo.middleware.simple_proxy.SimpleProxyMiddleware',
949
+ ]
950
+
951
+ # 配置代理列表
952
+ PROXY_ENABLED = True
953
+ PROXY_LIST = [
954
+ "http://proxy1.example.com:8080",
955
+ "http://proxy2.example.com:8080",
956
+ ]
957
+ ```
958
+
959
+ 有关代理中间件的详细使用说明,请参考[代理中间件示例项目](examples/simple_proxy_example/)。
960
+
961
+ ### 管道系统
962
+ 可扩展的数据处理管道,支持多种存储方式(控制台、数据库等)和去重功能:
963
+ - **ConsolePipeline**: 控制台输出管道
964
+ - **JsonPipeline**: JSON文件存储管道
965
+ - **RedisDedupPipeline**: Redis去重管道,基于Redis集合实现分布式去重
966
+ - **AsyncmyMySQLPipeline**: MySQL数据库存储管道,基于asyncmy驱动
967
+
968
+ ### 扩展组件
969
+ 功能增强扩展,包括日志、监控、性能分析等:
970
+ - **LogIntervalExtension**: 定时日志扩展
971
+ - **LogStats**: 统计日志扩展
972
+ - **CustomLoggerExtension**: 自定义日志扩展
973
+ - **MemoryMonitorExtension**: 内存监控扩展(监控爬虫进程内存使用情况)
974
+ - **PerformanceProfilerExtension**: 性能分析扩展
975
+ - **HealthCheckExtension**: 健康检查扩展
976
+ - **RequestRecorderExtension**: 请求记录扩展
977
+
978
+ ### 过滤系统
979
+ 智能去重过滤,支持多种去重策略(内存、Redis、Bloom Filter)。
980
+
981
+ ---
982
+
983
+ <!-- 示例项目 section -->
984
+ <h2 align="center">📦 示例项目</h2>
985
+
986
+ - [OFweek分布式爬虫](examples/ofweek_distributed/) - 复杂的分布式爬虫示例,包含Redis去重功能
987
+ - [OFweek独立爬虫](examples/ofweek_standalone/) - 独立运行的爬虫示例
988
+ - [OFweek混合模式爬虫](examples/ofweek_spider/) - 支持单机和分布式模式切换的爬虫示例
989
+
990
+ ---
991
+
992
+ <!-- 文档 section -->
993
+ <h2 align="center">📚 文档</h2>
994
+
995
+ 完整的文档请访问 [Crawlo Documentation](https://crawlo.readthedocs.io/)
996
+
997
+ - [快速开始指南](docs/modules/index.md)
998
+ - [模块化文档](docs/modules/index.md)
999
+ - [核心引擎文档](docs/modules/core/engine.md)
1000
+ - [调度器文档](docs/modules/core/scheduler.md)
1001
+ - [下载器文档](docs/modules/downloader/index.md)
1002
+ - [中间件文档](docs/modules/middleware/index.md)
1003
+ - [管道文档](docs/modules/pipeline/index.md)
1004
+ - [队列文档](docs/modules/queue/index.md)
1005
+ - [过滤器文档](docs/modules/filter/index.md)
1006
+ - [扩展组件文档](docs/modules/extension/index.md)
1007
+
1008
+ ---
1009
+
1010
+ <!-- 贡献 section -->
1011
+ <h2 align="center">🤝 贡献</h2>
1012
+
1013
+ 欢迎提交 Issue 和 Pull Request 来帮助改进 Crawlo!
1014
+
1015
+ ---
1016
+
1017
+ <!-- 许可证 section -->
1018
+ <h2 align="center">📄 许可证</h2>
1019
+
1020
+ 本项目采用 MIT 许可证,详情请见 [LICENSE](LICENSE) 文件。