crawlo 1.1.0__py3-none-any.whl → 1.1.2__py3-none-any.whl

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

Potentially problematic release.


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

Files changed (120) hide show
  1. crawlo/__init__.py +34 -24
  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 -155
  6. crawlo/commands/genspider.py +152 -111
  7. crawlo/commands/list.py +156 -119
  8. crawlo/commands/run.py +285 -170
  9. crawlo/commands/startproject.py +196 -101
  10. crawlo/commands/stats.py +188 -167
  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 +162 -57
  18. crawlo/crawler.py +1028 -493
  19. crawlo/downloader/__init__.py +242 -78
  20. crawlo/downloader/aiohttp_downloader.py +212 -199
  21. crawlo/downloader/cffi_downloader.py +252 -277
  22. crawlo/downloader/httpx_downloader.py +257 -246
  23. crawlo/event.py +11 -11
  24. crawlo/exceptions.py +78 -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 +269 -166
  49. crawlo/pipelines/__init__.py +13 -13
  50. crawlo/pipelines/console_pipeline.py +39 -39
  51. crawlo/pipelines/csv_pipeline.py +317 -0
  52. crawlo/pipelines/json_pipeline.py +219 -0
  53. crawlo/pipelines/mongo_pipeline.py +116 -116
  54. crawlo/pipelines/mysql_pipeline.py +195 -195
  55. crawlo/pipelines/pipeline_manager.py +56 -56
  56. crawlo/project.py +153 -0
  57. crawlo/queue/pqueue.py +37 -0
  58. crawlo/queue/queue_manager.py +304 -0
  59. crawlo/queue/redis_priority_queue.py +192 -0
  60. crawlo/settings/__init__.py +7 -7
  61. crawlo/settings/default_settings.py +226 -169
  62. crawlo/settings/setting_manager.py +99 -99
  63. crawlo/spider/__init__.py +639 -129
  64. crawlo/stats_collector.py +59 -59
  65. crawlo/subscriber.py +106 -106
  66. crawlo/task_manager.py +30 -27
  67. crawlo/templates/crawlo.cfg.tmpl +10 -10
  68. crawlo/templates/project/__init__.py.tmpl +3 -3
  69. crawlo/templates/project/items.py.tmpl +17 -17
  70. crawlo/templates/project/middlewares.py.tmpl +87 -76
  71. crawlo/templates/project/pipelines.py.tmpl +336 -64
  72. crawlo/templates/project/run.py.tmpl +239 -0
  73. crawlo/templates/project/settings.py.tmpl +248 -54
  74. crawlo/templates/project/spiders/__init__.py.tmpl +5 -5
  75. crawlo/templates/spider/spider.py.tmpl +178 -32
  76. crawlo/utils/__init__.py +7 -7
  77. crawlo/utils/controlled_spider_mixin.py +336 -0
  78. crawlo/utils/date_tools.py +233 -233
  79. crawlo/utils/db_helper.py +343 -343
  80. crawlo/utils/func_tools.py +82 -82
  81. crawlo/utils/large_scale_config.py +287 -0
  82. crawlo/utils/large_scale_helper.py +344 -0
  83. crawlo/utils/log.py +128 -128
  84. crawlo/utils/queue_helper.py +176 -0
  85. crawlo/utils/request.py +267 -267
  86. crawlo/utils/request_serializer.py +220 -0
  87. crawlo/utils/spider_loader.py +62 -62
  88. crawlo/utils/system.py +11 -11
  89. crawlo/utils/tools.py +4 -4
  90. crawlo/utils/url.py +39 -39
  91. crawlo-1.1.2.dist-info/METADATA +567 -0
  92. crawlo-1.1.2.dist-info/RECORD +108 -0
  93. examples/__init__.py +7 -0
  94. tests/__init__.py +7 -7
  95. tests/test_final_validation.py +154 -0
  96. tests/test_proxy_health_check.py +32 -32
  97. tests/test_proxy_middleware_integration.py +136 -136
  98. tests/test_proxy_providers.py +56 -56
  99. tests/test_proxy_stats.py +19 -19
  100. tests/test_proxy_strategies.py +59 -59
  101. tests/test_redis_config.py +29 -0
  102. tests/test_redis_queue.py +225 -0
  103. tests/test_request_serialization.py +71 -0
  104. tests/test_scheduler.py +242 -0
  105. crawlo/pipelines/mysql_batch_pipline.py +0 -273
  106. crawlo/utils/concurrency_manager.py +0 -125
  107. crawlo/utils/pqueue.py +0 -174
  108. crawlo/utils/project.py +0 -197
  109. crawlo-1.1.0.dist-info/METADATA +0 -49
  110. crawlo-1.1.0.dist-info/RECORD +0 -97
  111. examples/gxb/items.py +0 -36
  112. examples/gxb/run.py +0 -16
  113. examples/gxb/settings.py +0 -72
  114. examples/gxb/spider/__init__.py +0 -2
  115. examples/gxb/spider/miit_spider.py +0 -180
  116. examples/gxb/spider/telecom_device.py +0 -129
  117. {examples/gxb → crawlo/queue}/__init__.py +0 -0
  118. {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
  119. {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
  120. {crawlo-1.1.0.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
@@ -1,101 +1,196 @@
1
- # crawlo/commands/startproject.py
2
- import os
3
- import shutil
4
- from pathlib import Path
5
-
6
- TEMPLATES_DIR = Path(__file__).parent.parent / 'templates'
7
-
8
-
9
- def _render_template(tmpl_path, context):
10
- """读取模板文件,替换 {{key}} context 中的值"""
11
- with open(tmpl_path, 'r', encoding='utf-8') as f:
12
- content = f.read()
13
- for key, value in context.items():
14
- content = content.replace(f'{{{{{key}}}}}', str(value))
15
- return content
16
-
17
-
18
- def _copytree_with_templates(src, dst, context):
19
- """
20
- 递归复制目录,将 .tmpl 文件渲染后复制(去除 .tmpl 后缀),其他文件直接复制。
21
- """
22
- src_path = Path(src)
23
- dst_path = Path(dst)
24
- dst_path.mkdir(parents=True, exist_ok=True)
25
-
26
- for item in src_path.rglob('*'):
27
- rel_path = item.relative_to(src_path)
28
- dst_item = dst_path / rel_path
29
-
30
- if item.is_dir():
31
- # 创建目标目录
32
- dst_item.mkdir(parents=True, exist_ok=True)
33
- else:
34
- if item.suffix == '.tmpl':
35
- # 渲染模板文件,并去掉 .tmpl 后缀
36
- rendered_content = _render_template(item, context)
37
- final_dst = dst_item.with_suffix('') # 去掉 .tmpl
38
- final_dst.parent.mkdir(parents=True, exist_ok=True) # 确保父目录存在
39
- with open(final_dst, 'w', encoding='utf-8') as f:
40
- f.write(rendered_content)
41
- else:
42
- # 普通文件,直接复制
43
- shutil.copy2(item, dst_item)
44
-
45
-
46
- def main(args):
47
- if len(args) != 1:
48
- print("Usage: crawlo startproject <project_name>")
49
- return 1
50
-
51
- project_name = args[0]
52
- project_dir = Path(project_name)
53
-
54
- if project_dir.exists():
55
- print(f"Error: Directory '{project_dir}' already exists.")
56
- return 1
57
-
58
- context = {'project_name': project_name}
59
- template_dir = TEMPLATES_DIR / 'project'
60
-
61
- try:
62
- # 1. 创建项目根目录
63
- project_dir.mkdir()
64
-
65
- # 2. 处理 crawlo.cfg.tmpl:单独渲染并写入项目根目录
66
- cfg_template = TEMPLATES_DIR / 'crawlo.cfg.tmpl' # 使用 templates/ 目录下的模板
67
- if cfg_template.exists():
68
- cfg_content = _render_template(cfg_template, context)
69
- (project_dir / 'crawlo.cfg').write_text(cfg_content, encoding='utf-8')
70
- else:
71
- print("Warning: crawlo.cfg.tmpl not found in templates.")
72
-
73
- # 3. 复制所有其他模板文件到项目包内 (project_dir / project_name)
74
- package_dir = project_dir / project_name
75
- # 这会复制 __init__.py.tmpl, items.py.tmpl, settings.py.tmpl, spiders/ 等
76
- # 并将它们渲染为 .py 文件
77
- _copytree_with_templates(template_dir, package_dir, context)
78
-
79
- # 4. 创建 logs 目录
80
- (project_dir / 'logs').mkdir(exist_ok=True)
81
-
82
- print(f"""
83
- 项目 '{project_name}' 创建成功!
84
-
85
- 进入项目目录:
86
- cd {project_name}
87
-
88
- 创建一个爬虫:
89
- crawlo genspider example example.com
90
-
91
- 运行爬虫:
92
- crawlo run example
93
- """)
94
- return 0
95
-
96
- except Exception as e:
97
- print(f"Error creating project: {e}")
98
- # 如果出错,尝试清理已创建的目录
99
- if project_dir.exists():
100
- shutil.rmtree(project_dir, ignore_errors=True)
101
- 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