crawlo 1.1.1__py3-none-any.whl → 1.1.3__py3-none-any.whl

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

Potentially problematic release.


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

Files changed (128) hide show
  1. crawlo/__init__.py +34 -33
  2. crawlo/__version__.py +1 -1
  3. crawlo/cli.py +40 -40
  4. crawlo/commands/__init__.py +13 -13
  5. crawlo/commands/check.py +594 -594
  6. crawlo/commands/genspider.py +152 -126
  7. crawlo/commands/list.py +156 -147
  8. crawlo/commands/run.py +285 -285
  9. crawlo/commands/startproject.py +196 -111
  10. crawlo/commands/stats.py +188 -188
  11. crawlo/commands/utils.py +187 -0
  12. crawlo/config.py +280 -0
  13. crawlo/core/__init__.py +2 -2
  14. crawlo/core/engine.py +171 -158
  15. crawlo/core/enhanced_engine.py +190 -0
  16. crawlo/core/processor.py +40 -40
  17. crawlo/core/scheduler.py +166 -57
  18. crawlo/crawler.py +1028 -495
  19. crawlo/downloader/__init__.py +242 -78
  20. crawlo/downloader/aiohttp_downloader.py +212 -199
  21. crawlo/downloader/cffi_downloader.py +251 -241
  22. crawlo/downloader/httpx_downloader.py +259 -246
  23. crawlo/event.py +11 -11
  24. crawlo/exceptions.py +82 -78
  25. crawlo/extension/__init__.py +31 -31
  26. crawlo/extension/log_interval.py +49 -49
  27. crawlo/extension/log_stats.py +44 -44
  28. crawlo/extension/logging_extension.py +34 -34
  29. crawlo/filters/__init__.py +154 -37
  30. crawlo/filters/aioredis_filter.py +242 -150
  31. crawlo/filters/memory_filter.py +269 -202
  32. crawlo/items/__init__.py +23 -23
  33. crawlo/items/base.py +21 -21
  34. crawlo/items/fields.py +53 -53
  35. crawlo/items/items.py +104 -104
  36. crawlo/middleware/__init__.py +21 -21
  37. crawlo/middleware/default_header.py +32 -32
  38. crawlo/middleware/download_delay.py +28 -28
  39. crawlo/middleware/middleware_manager.py +135 -135
  40. crawlo/middleware/proxy.py +248 -245
  41. crawlo/middleware/request_ignore.py +30 -30
  42. crawlo/middleware/response_code.py +18 -18
  43. crawlo/middleware/response_filter.py +26 -26
  44. crawlo/middleware/retry.py +125 -90
  45. crawlo/mode_manager.py +201 -0
  46. crawlo/network/__init__.py +21 -7
  47. crawlo/network/request.py +311 -203
  48. crawlo/network/response.py +271 -166
  49. crawlo/pipelines/__init__.py +22 -13
  50. crawlo/pipelines/bloom_dedup_pipeline.py +157 -0
  51. crawlo/pipelines/console_pipeline.py +39 -39
  52. crawlo/pipelines/csv_pipeline.py +317 -0
  53. crawlo/pipelines/database_dedup_pipeline.py +225 -0
  54. crawlo/pipelines/json_pipeline.py +219 -0
  55. crawlo/pipelines/memory_dedup_pipeline.py +116 -0
  56. crawlo/pipelines/mongo_pipeline.py +116 -116
  57. crawlo/pipelines/mysql_pipeline.py +195 -195
  58. crawlo/pipelines/pipeline_manager.py +56 -56
  59. crawlo/pipelines/redis_dedup_pipeline.py +163 -0
  60. crawlo/project.py +153 -153
  61. crawlo/queue/__init__.py +0 -0
  62. crawlo/queue/pqueue.py +37 -0
  63. crawlo/queue/queue_manager.py +308 -0
  64. crawlo/queue/redis_priority_queue.py +209 -0
  65. crawlo/settings/__init__.py +7 -7
  66. crawlo/settings/default_settings.py +245 -167
  67. crawlo/settings/setting_manager.py +99 -99
  68. crawlo/spider/__init__.py +639 -129
  69. crawlo/stats_collector.py +59 -59
  70. crawlo/subscriber.py +106 -106
  71. crawlo/task_manager.py +30 -27
  72. crawlo/templates/crawlo.cfg.tmpl +10 -10
  73. crawlo/templates/project/__init__.py.tmpl +3 -3
  74. crawlo/templates/project/items.py.tmpl +17 -17
  75. crawlo/templates/project/middlewares.py.tmpl +87 -76
  76. crawlo/templates/project/pipelines.py.tmpl +342 -64
  77. crawlo/templates/project/run.py.tmpl +252 -0
  78. crawlo/templates/project/settings.py.tmpl +251 -54
  79. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  80. crawlo/templates/spider/spider.py.tmpl +178 -32
  81. crawlo/utils/__init__.py +7 -7
  82. crawlo/utils/controlled_spider_mixin.py +440 -0
  83. crawlo/utils/date_tools.py +233 -233
  84. crawlo/utils/db_helper.py +343 -343
  85. crawlo/utils/func_tools.py +82 -82
  86. crawlo/utils/large_scale_config.py +287 -0
  87. crawlo/utils/large_scale_helper.py +344 -0
  88. crawlo/utils/log.py +128 -128
  89. crawlo/utils/queue_helper.py +176 -0
  90. crawlo/utils/request.py +267 -267
  91. crawlo/utils/request_serializer.py +220 -0
  92. crawlo/utils/spider_loader.py +62 -62
  93. crawlo/utils/system.py +11 -11
  94. crawlo/utils/tools.py +4 -4
  95. crawlo/utils/url.py +39 -39
  96. crawlo-1.1.3.dist-info/METADATA +635 -0
  97. crawlo-1.1.3.dist-info/RECORD +113 -0
  98. examples/__init__.py +7 -7
  99. examples/controlled_spider_example.py +205 -0
  100. tests/__init__.py +7 -7
  101. tests/test_final_validation.py +154 -0
  102. tests/test_proxy_health_check.py +32 -32
  103. tests/test_proxy_middleware_integration.py +136 -136
  104. tests/test_proxy_providers.py +56 -56
  105. tests/test_proxy_stats.py +19 -19
  106. tests/test_proxy_strategies.py +59 -59
  107. tests/test_redis_config.py +29 -0
  108. tests/test_redis_queue.py +225 -0
  109. tests/test_request_serialization.py +71 -0
  110. tests/test_scheduler.py +242 -0
  111. crawlo/pipelines/mysql_batch_pipline.py +0 -273
  112. crawlo/utils/pqueue.py +0 -174
  113. crawlo-1.1.1.dist-info/METADATA +0 -220
  114. crawlo-1.1.1.dist-info/RECORD +0 -100
  115. examples/baidu_spider/__init__.py +0 -7
  116. examples/baidu_spider/demo.py +0 -94
  117. examples/baidu_spider/items.py +0 -46
  118. examples/baidu_spider/middleware.py +0 -49
  119. examples/baidu_spider/pipeline.py +0 -55
  120. examples/baidu_spider/run.py +0 -27
  121. examples/baidu_spider/settings.py +0 -121
  122. examples/baidu_spider/spiders/__init__.py +0 -7
  123. examples/baidu_spider/spiders/bai_du.py +0 -61
  124. examples/baidu_spider/spiders/miit.py +0 -159
  125. examples/baidu_spider/spiders/sina.py +0 -79
  126. {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/WHEEL +0 -0
  127. {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/entry_points.txt +0 -0
  128. {crawlo-1.1.1.dist-info → crawlo-1.1.3.dist-info}/top_level.txt +0 -0
@@ -1,111 +1,196 @@
1
- #!/usr/bin/python
2
- # -*- coding: UTF-8 -*-
3
- """
4
- # @Time : 2025-08-31 22:36
5
- # @Author : crawl-coder
6
- # @Desc : 命令行入口:crawlo startproject baidu,创建项目。
7
- """
8
- import shutil
9
- from pathlib import Path
10
- from rich.console import Console
11
- from rich.panel import Panel
12
- from rich.text import Text
13
-
14
- # 初始化 rich 控制台
15
- console = Console()
16
-
17
- TEMPLATES_DIR = Path(__file__).parent.parent / 'templates'
18
-
19
-
20
- def _render_template(tmpl_path, context):
21
- """读取模板文件,替换 {{key}} 为 context 中的值"""
22
- with open(tmpl_path, 'r', encoding='utf-8') as f:
23
- content = f.read()
24
- for key, value in context.items():
25
- content = content.replace(f'{{{{{key}}}}}', str(value))
26
- return content
27
-
28
-
29
- def _copytree_with_templates(src, dst, context):
30
- """
31
- 递归复制目录,将 .tmpl 文件渲染后复制(去除 .tmpl 后缀),其他文件直接复制。
32
- """
33
- src_path = Path(src)
34
- dst_path = Path(dst)
35
- dst_path.mkdir(parents=True, exist_ok=True)
36
-
37
- for item in src_path.rglob('*'):
38
- rel_path = item.relative_to(src_path)
39
- dst_item = dst_path / rel_path
40
-
41
- if item.is_dir():
42
- dst_item.mkdir(parents=True, exist_ok=True)
43
- else:
44
- if item.suffix == '.tmpl':
45
- rendered_content = _render_template(item, context)
46
- final_dst = dst_item.with_suffix('')
47
- final_dst.parent.mkdir(parents=True, exist_ok=True)
48
- with open(final_dst, 'w', encoding='utf-8') as f:
49
- f.write(rendered_content)
50
- else:
51
- shutil.copy2(item, dst_item)
52
-
53
-
54
- def main(args):
55
- if len(args) != 1:
56
- console.print("[bold red]Error:[/bold red] Usage: crawlo startproject <project_name>")
57
- return 1
58
-
59
- project_name = args[0]
60
- project_dir = Path(project_name)
61
-
62
- if project_dir.exists():
63
- console.print(f"[bold red]Error:[/bold red] Directory '[cyan]{project_dir}[/cyan]' already exists.")
64
- return 1
65
-
66
- context = {'project_name': project_name}
67
- template_dir = TEMPLATES_DIR / 'project'
68
-
69
- try:
70
- # 1. 创建项目根目录
71
- project_dir.mkdir()
72
-
73
- # 2. 渲染 crawlo.cfg.tmpl
74
- cfg_template = TEMPLATES_DIR / 'crawlo.cfg.tmpl'
75
- if cfg_template.exists():
76
- cfg_content = _render_template(cfg_template, context)
77
- (project_dir / 'crawlo.cfg').write_text(cfg_content, encoding='utf-8')
78
- console.print(f":white_check_mark: Created [green]{project_dir / 'crawlo.cfg'}[/green]")
79
- else:
80
- console.print("[yellow]⚠ Warning:[/yellow] Template 'crawlo.cfg.tmpl' not found.")
81
-
82
- # 3. 复制并渲染项目包内容
83
- package_dir = project_dir / project_name
84
- _copytree_with_templates(template_dir, package_dir, context)
85
- console.print(f":white_check_mark: Created project package: [green]{package_dir}[/green]")
86
-
87
- # 4. 创建 logs 目录
88
- (project_dir / 'logs').mkdir(exist_ok=True)
89
- console.print(":white_check_mark: Created logs directory")
90
-
91
- # 成功面板
92
- success_text = Text.from_markup(f"Project '[bold cyan]{project_name}[/bold cyan]' created successfully!")
93
- console.print(Panel(success_text, title=":rocket: Success", border_style="green", padding=(1, 2)))
94
-
95
- # 下一步操作提示(对齐美观 + 语法高亮)
96
- next_steps = f"""
97
- [bold]Next steps:[/bold]
98
- [blue]cd[/blue] {project_name}
99
- [blue]crawlo genspider[/blue] example example.com
100
- [blue]crawlo run[/blue] example
101
- """.strip()
102
- console.print(next_steps)
103
-
104
- return 0
105
-
106
- except Exception as e:
107
- console.print(f"[bold red]Error creating project:[/bold red] {e}")
108
- if project_dir.exists():
109
- shutil.rmtree(project_dir, ignore_errors=True)
110
- console.print("[red]:cross_mark: Cleaned up partially created project.[/red]")
111
- return 1
1
+ #!/usr/bin/python
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ # @Time : 2025-08-31 22:36
5
+ # @Author : crawl-coder
6
+ # @Desc : 命令行入口:crawlo startproject baidu,创建项目。
7
+ """
8
+ import shutil
9
+ import re
10
+ from pathlib import Path
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+ from rich.text import Text
14
+
15
+ from .utils import show_error_panel, show_success_panel
16
+
17
+ # 初始化 rich 控制台
18
+ console = Console()
19
+
20
+ TEMPLATES_DIR = Path(__file__).parent.parent / 'templates'
21
+
22
+
23
+ def _render_template(tmpl_path, context):
24
+ """读取模板文件,替换 {{key}} context 中的值"""
25
+ with open(tmpl_path, 'r', encoding='utf-8') as f:
26
+ content = f.read()
27
+ for key, value in context.items():
28
+ content = content.replace(f'{{{{{key}}}}}', str(value))
29
+ return content
30
+
31
+
32
+ def _copytree_with_templates(src, dst, context):
33
+ """
34
+ 递归复制目录,将 .tmpl 文件渲染后复制(去除 .tmpl 后缀),其他文件直接复制。
35
+ """
36
+ src_path = Path(src)
37
+ dst_path = Path(dst)
38
+ dst_path.mkdir(parents=True, exist_ok=True)
39
+
40
+ for item in src_path.rglob('*'):
41
+ rel_path = item.relative_to(src_path)
42
+ dst_item = dst_path / rel_path
43
+
44
+ if item.is_dir():
45
+ dst_item.mkdir(parents=True, exist_ok=True)
46
+ else:
47
+ if item.suffix == '.tmpl':
48
+ rendered_content = _render_template(item, context)
49
+ final_dst = dst_item.with_suffix('')
50
+ final_dst.parent.mkdir(parents=True, exist_ok=True)
51
+ with open(final_dst, 'w', encoding='utf-8') as f:
52
+ f.write(rendered_content)
53
+ else:
54
+ shutil.copy2(item, dst_item)
55
+
56
+
57
+ def validate_project_name(project_name: str) -> tuple[bool, str]:
58
+ """
59
+ 验证项目名称是否有效
60
+
61
+ Returns:
62
+ tuple[bool, str]: (是否有效, 错误信息)
63
+ """
64
+ # 检查是否为空
65
+ if not project_name or not project_name.strip():
66
+ return False, "Project name cannot be empty"
67
+
68
+ project_name = project_name.strip()
69
+
70
+ # 检查长度
71
+ if len(project_name) > 50:
72
+ return False, "Project name too long (max 50 characters)"
73
+
74
+ # 检查是否为Python关键字
75
+ python_keywords = {
76
+ 'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class',
77
+ 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
78
+ 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
79
+ 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
80
+ 'while', 'with', 'yield'
81
+ }
82
+ if project_name in python_keywords:
83
+ return False, f"'{project_name}' is a Python keyword and cannot be used as project name"
84
+
85
+ # 检查是否为有效的Python标识符
86
+ if not project_name.isidentifier():
87
+ return False, "Project name must be a valid Python identifier"
88
+
89
+ # 检查格式(建议使用snake_case)
90
+ if not re.match(r'^[a-z][a-z0-9_]*$', project_name):
91
+ return False, (
92
+ "Project name should start with lowercase letter and "
93
+ "contain only lowercase letters, numbers, and underscores"
94
+ )
95
+
96
+ # 检查是否以数字结尾(不推荐)
97
+ if project_name[-1].isdigit():
98
+ return False, "Project name should not end with a number"
99
+
100
+ return True, ""
101
+
102
+
103
+ def main(args):
104
+ if len(args) != 1:
105
+ console.print("[bold red]Error:[/bold red] Usage: [blue]crawlo startproject[/blue] <project_name>")
106
+ console.print("💡 Examples:")
107
+ console.print(" [blue]crawlo startproject[/blue] my_spider_project")
108
+ console.print(" [blue]crawlo startproject[/blue] news_crawler")
109
+ console.print(" [blue]crawlo startproject[/blue] ecommerce_spider")
110
+ return 1
111
+
112
+ project_name = args[0]
113
+
114
+ # 验证项目名称
115
+ is_valid, error_msg = validate_project_name(project_name)
116
+ if not is_valid:
117
+ show_error_panel(
118
+ "Invalid Project Name",
119
+ f"[cyan]{project_name}[/cyan] is not a valid project name.\n"
120
+ f"❌ {error_msg}\n\n"
121
+ "💡 Project name should:\n"
122
+ " • Start with lowercase letter\n"
123
+ " • Contain only lowercase letters, numbers, and underscores\n"
124
+ " • Be a valid Python identifier\n"
125
+ " • Not be a Python keyword"
126
+ )
127
+ return 1
128
+
129
+ project_dir = Path(project_name)
130
+
131
+ if project_dir.exists():
132
+ show_error_panel(
133
+ "Directory Exists",
134
+ f"Directory '[cyan]{project_dir}[/cyan]' already exists.\n"
135
+ "💡 Choose a different project name or remove the existing directory."
136
+ )
137
+ return 1
138
+
139
+ context = {'project_name': project_name}
140
+ template_dir = TEMPLATES_DIR / 'project'
141
+
142
+ try:
143
+ # 1. 创建项目根目录
144
+ project_dir.mkdir()
145
+
146
+ # 2. 渲染 crawlo.cfg.tmpl
147
+ cfg_template = TEMPLATES_DIR / 'crawlo.cfg.tmpl'
148
+ if cfg_template.exists():
149
+ cfg_content = _render_template(cfg_template, context)
150
+ (project_dir / 'crawlo.cfg').write_text(cfg_content, encoding='utf-8')
151
+ console.print(f":white_check_mark: Created [green]{project_dir / 'crawlo.cfg'}[/green]")
152
+ else:
153
+ console.print("[yellow]⚠ Warning:[/yellow] Template 'crawlo.cfg.tmpl' not found.")
154
+
155
+ # 3. 复制并渲染项目包内容
156
+ package_dir = project_dir / project_name
157
+ _copytree_with_templates(template_dir, package_dir, context)
158
+ console.print(f":white_check_mark: Created project package: [green]{package_dir}[/green]")
159
+
160
+ # 4. 创建 logs 目录
161
+ (project_dir / 'logs').mkdir(exist_ok=True)
162
+ console.print(":white_check_mark: Created logs directory")
163
+
164
+ # 5. 创建 output 目录(用于数据输出)
165
+ (project_dir / 'output').mkdir(exist_ok=True)
166
+ console.print(":white_check_mark: Created output directory")
167
+
168
+ # 成功面板
169
+ success_text = Text.from_markup(f"Project '[bold cyan]{project_name}[/bold cyan]' created successfully!")
170
+ console.print(Panel(success_text, title=":rocket: Success", border_style="green", padding=(1, 2)))
171
+
172
+ # 下一步操作提示(对齐美观 + 语法高亮)
173
+ next_steps = f"""
174
+ [bold]🚀 Next steps:[/bold]
175
+ [blue]cd[/blue] {project_name}
176
+ [blue]crawlo genspider[/blue] example example.com
177
+ [blue]crawlo run[/blue] example
178
+
179
+ [bold]📚 Learn more:[/bold]
180
+ [blue]crawlo list[/blue] # List all spiders
181
+ [blue]crawlo check[/blue] example # Check spider validity
182
+ [blue]crawlo stats[/blue] # View statistics
183
+ """.strip()
184
+ console.print(next_steps)
185
+
186
+ return 0
187
+
188
+ except Exception as e:
189
+ show_error_panel(
190
+ "Creation Failed",
191
+ f"Failed to create project: {e}"
192
+ )
193
+ if project_dir.exists():
194
+ shutil.rmtree(project_dir, ignore_errors=True)
195
+ console.print("[red]:cross_mark: Cleaned up partially created project.[/red]")
196
+ return 1