crawlo 1.4.3__py3-none-any.whl → 1.4.5__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 (107) hide show
  1. crawlo/__init__.py +11 -15
  2. crawlo/__version__.py +1 -1
  3. crawlo/commands/genspider.py +52 -17
  4. crawlo/commands/startproject.py +24 -0
  5. crawlo/core/engine.py +2 -2
  6. crawlo/core/scheduler.py +4 -4
  7. crawlo/crawler.py +13 -6
  8. crawlo/downloader/__init__.py +5 -2
  9. crawlo/extension/__init__.py +2 -2
  10. crawlo/filters/aioredis_filter.py +8 -1
  11. crawlo/filters/memory_filter.py +8 -1
  12. crawlo/initialization/built_in.py +13 -4
  13. crawlo/initialization/core.py +5 -4
  14. crawlo/interfaces.py +24 -0
  15. crawlo/middleware/__init__.py +7 -4
  16. crawlo/middleware/middleware_manager.py +15 -8
  17. crawlo/mode_manager.py +45 -11
  18. crawlo/network/response.py +374 -69
  19. crawlo/pipelines/mysql_pipeline.py +6 -6
  20. crawlo/pipelines/pipeline_manager.py +2 -2
  21. crawlo/project.py +2 -4
  22. crawlo/queue/pqueue.py +2 -6
  23. crawlo/queue/queue_manager.py +1 -2
  24. crawlo/settings/default_settings.py +15 -30
  25. crawlo/task_manager.py +2 -2
  26. crawlo/templates/project/items.py.tmpl +2 -2
  27. crawlo/templates/project/middlewares.py.tmpl +9 -89
  28. crawlo/templates/project/pipelines.py.tmpl +8 -68
  29. crawlo/templates/project/settings.py.tmpl +51 -65
  30. crawlo/templates/project/settings_distributed.py.tmpl +59 -67
  31. crawlo/templates/project/settings_gentle.py.tmpl +45 -40
  32. crawlo/templates/project/settings_high_performance.py.tmpl +45 -40
  33. crawlo/templates/project/settings_minimal.py.tmpl +37 -26
  34. crawlo/templates/project/settings_simple.py.tmpl +45 -40
  35. crawlo/templates/run.py.tmpl +3 -7
  36. crawlo/tools/__init__.py +0 -11
  37. crawlo/utils/__init__.py +17 -1
  38. crawlo/utils/db_helper.py +220 -319
  39. crawlo/utils/error_handler.py +313 -67
  40. crawlo/utils/fingerprint.py +3 -4
  41. crawlo/utils/misc.py +82 -0
  42. crawlo/utils/request.py +55 -66
  43. crawlo/utils/selector_helper.py +138 -0
  44. crawlo/utils/spider_loader.py +185 -45
  45. crawlo/utils/text_helper.py +95 -0
  46. crawlo-1.4.5.dist-info/METADATA +329 -0
  47. {crawlo-1.4.3.dist-info → crawlo-1.4.5.dist-info}/RECORD +89 -68
  48. tests/bug_check_test.py +251 -0
  49. tests/direct_selector_helper_test.py +97 -0
  50. tests/ofweek_scrapy/ofweek_scrapy/items.py +12 -0
  51. tests/ofweek_scrapy/ofweek_scrapy/middlewares.py +100 -0
  52. tests/ofweek_scrapy/ofweek_scrapy/pipelines.py +13 -0
  53. tests/ofweek_scrapy/ofweek_scrapy/settings.py +85 -0
  54. tests/ofweek_scrapy/ofweek_scrapy/spiders/__init__.py +4 -0
  55. tests/ofweek_scrapy/ofweek_scrapy/spiders/ofweek_spider.py +162 -0
  56. tests/ofweek_scrapy/scrapy.cfg +11 -0
  57. tests/performance_comparison.py +4 -5
  58. tests/simple_crawlo_test.py +1 -2
  59. tests/simple_follow_test.py +39 -0
  60. tests/simple_response_selector_test.py +95 -0
  61. tests/simple_selector_helper_test.py +155 -0
  62. tests/simple_selector_test.py +208 -0
  63. tests/simple_url_test.py +74 -0
  64. tests/test_crawler_process_import.py +39 -0
  65. tests/test_crawler_process_spider_modules.py +48 -0
  66. tests/test_edge_cases.py +7 -5
  67. tests/test_encoding_core.py +57 -0
  68. tests/test_encoding_detection.py +127 -0
  69. tests/test_factory_compatibility.py +197 -0
  70. tests/test_multi_directory.py +68 -0
  71. tests/test_multiple_spider_modules.py +81 -0
  72. tests/test_optimized_selector_naming.py +101 -0
  73. tests/test_priority_behavior.py +18 -18
  74. tests/test_response_follow.py +105 -0
  75. tests/test_response_selector_methods.py +93 -0
  76. tests/test_response_url_methods.py +71 -0
  77. tests/test_response_urljoin.py +87 -0
  78. tests/test_scrapy_style_encoding.py +113 -0
  79. tests/test_selector_helper.py +101 -0
  80. tests/test_selector_optimizations.py +147 -0
  81. tests/test_spider_loader.py +50 -0
  82. tests/test_spider_loader_comprehensive.py +70 -0
  83. tests/test_spider_modules.py +85 -0
  84. tests/test_spiders/__init__.py +1 -0
  85. tests/test_spiders/test_spider.py +10 -0
  86. crawlo/tools/anti_crawler.py +0 -269
  87. crawlo/utils/class_loader.py +0 -26
  88. crawlo/utils/enhanced_error_handler.py +0 -357
  89. crawlo-1.4.3.dist-info/METADATA +0 -190
  90. examples/test_project/__init__.py +0 -7
  91. examples/test_project/run.py +0 -35
  92. examples/test_project/test_project/__init__.py +0 -4
  93. examples/test_project/test_project/items.py +0 -18
  94. examples/test_project/test_project/middlewares.py +0 -119
  95. examples/test_project/test_project/pipelines.py +0 -97
  96. examples/test_project/test_project/settings.py +0 -170
  97. examples/test_project/test_project/spiders/__init__.py +0 -10
  98. examples/test_project/test_project/spiders/of_week_dis.py +0 -144
  99. tests/simple_log_test.py +0 -58
  100. tests/simple_test.py +0 -48
  101. tests/test_framework_logger.py +0 -67
  102. tests/test_framework_startup.py +0 -65
  103. tests/test_mode_change.py +0 -73
  104. {crawlo-1.4.3.dist-info → crawlo-1.4.5.dist-info}/WHEEL +0 -0
  105. {crawlo-1.4.3.dist-info → crawlo-1.4.5.dist-info}/entry_points.txt +0 -0
  106. {crawlo-1.4.3.dist-info → crawlo-1.4.5.dist-info}/top_level.txt +0 -0
  107. /tests/{final_command_test_report.md → ofweek_scrapy/ofweek_scrapy/__init__.py} +0 -0
@@ -1,119 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- test_project.middlewares
4
- ============================
5
- 自定义中间件,用于在请求/响应/异常处理过程中插入自定义逻辑。
6
-
7
- 这是一个简单的示例中间件,您可以根据需要添加更多中间件。
8
- """
9
-
10
- import random
11
- from crawlo import Request, Response
12
- from crawlo.utils.log import get_logger
13
-
14
-
15
- class ExampleMiddleware:
16
- """
17
- 示例中间件,演示如何处理请求、响应和异常。
18
-
19
- 此中间件会:
20
- 1. 为请求添加随机 User-Agent
21
- 2. 记录请求和响应信息
22
- 3. 处理异常情况
23
- """
24
-
25
- def __init__(self):
26
- self.logger = get_logger(self.__class__.__name__)
27
- self.user_agents = [
28
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
29
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
30
- 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0',
31
- 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:135.0) Gecko/20100101 Firefox/135.0',
32
- ]
33
-
34
- def process_request(self, request, spider):
35
- """
36
- 在请求被下载器执行前调用。
37
-
38
- Args:
39
- request: 请求对象
40
- spider: 爬虫实例
41
-
42
- Returns:
43
- None: 继续处理请求
44
- Response: 返回响应对象(短路处理)
45
- Request: 返回新请求对象(替换原请求)
46
- """
47
- # 为请求添加随机 User-Agent
48
- if 'User-Agent' not in request.headers:
49
- ua = random.choice(self.user_agents)
50
- request.headers['User-Agent'] = ua
51
- self.logger.debug(f"为请求 {request.url} 设置 User-Agent: {ua[:50]}...")
52
-
53
- return None
54
-
55
- def process_response(self, request, response, spider):
56
- """
57
- 在响应被 Spider 处理前调用。
58
-
59
- Args:
60
- request: 原始请求对象
61
- response: 响应对象
62
- spider: 爬虫实例
63
-
64
- Returns:
65
- Response: 处理后的响应对象
66
- """
67
- # 记录响应信息
68
- self.logger.info(f"收到响应: {request.url} - 状态码: {response.status_code}")
69
-
70
- # 可以在这里处理特殊状态码
71
- if response.status_code == 403:
72
- self.logger.warning(f"访问被拒绝: {request.url}")
73
-
74
- return response
75
-
76
- def process_exception(self, request, exception, spider):
77
- """
78
- 在下载或处理过程中发生异常时调用。
79
-
80
- Args:
81
- request: 请求对象
82
- exception: 异常对象
83
- spider: 爬虫实例
84
-
85
- Returns:
86
- None: 异常将继续传播
87
- Response: 返回响应对象(处理异常)
88
- Request: 返回新请求对象(重试请求)
89
- """
90
- self.logger.error(f"请求异常: {request.url} - {exception}")
91
- return None
92
-
93
-
94
- # ======================== 使用说明 ========================
95
- #
96
- # 在 settings.py 中启用中间件:
97
- # MIDDLEWARES = [
98
- # 'test_project.middlewares.ExampleMiddleware',
99
- # ]
100
- #
101
- # 您可以根据需要添加更多中间件,例如:
102
- # 1. 请求处理中间件(修改请求头、设置代理等)
103
- # 2. 响应处理中间件(解析、过滤等)
104
- # 3. 异常处理中间件(重试、记录等)
105
- #
106
- # 每个中间件可以实现以下方法:
107
- # - process_request: 处理请求
108
- # - process_response: 处理响应
109
- # - process_exception: 处理异常
110
- #
111
- # 注意:Crawlo框架提供了许多内置中间件,您可以直接使用:
112
- # - DownloadDelayMiddleware: 控制请求延迟
113
- # - ResponseCodeMiddleware: 处理HTTP状态码并记录统计信息
114
- # - ResponseFilterMiddleware: 过滤特定状态码的响应
115
- # - DefaultHeaderMiddleware: 添加默认请求头
116
- # - ProxyMiddleware: 设置代理
117
- # - RetryMiddleware: 处理重试逻辑
118
- # - OffsiteMiddleware: 过滤站外请求
119
- # ======================== 使用说明 ========================
@@ -1,97 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- test_project.pipelines
4
- ==========================
5
- 数据管道,用于处理 Spider 返回的 Item。
6
- 例如:清理、验证、去重、保存到数据库等。
7
-
8
- 这是一个简单的示例管道,您可以根据需要添加更多管道。
9
- """
10
-
11
- from datetime import datetime
12
- from crawlo.exceptions import DropItem
13
- from crawlo.utils.log import get_logger
14
-
15
-
16
- class ExamplePipeline:
17
- """
18
- 示例管道,演示如何处理数据项。
19
-
20
- 此管道会:
21
- 1. 验证必要字段
22
- 2. 清理数据
23
- 3. 添加时间戳
24
- 4. 记录处理日志
25
- """
26
-
27
- def __init__(self):
28
- self.logger = get_logger(self.__class__.__name__)
29
- self.item_count = 0
30
-
31
- def process_item(self, item, spider):
32
- """
33
- 处理数据项。
34
-
35
- Args:
36
- item: 要处理的数据项
37
- spider: 爬虫实例
38
-
39
- Returns:
40
- 处理后的数据项
41
-
42
- Raises:
43
- DropItem: 如果数据项无效则抛出此异常
44
- """
45
- # 验证必要字段
46
- if not item.get('title') or not item.get('url'):
47
- raise DropItem("缺少必要字段: title 或 url")
48
-
49
- # 数据清理
50
- item['title'] = str(item['title']).strip()
51
-
52
- # 添加处理时间戳
53
- item['processed_at'] = datetime.now().isoformat()
54
-
55
- # 计数器
56
- self.item_count += 1
57
-
58
- # 记录日志
59
- self.logger.info(f"处理第 {self.item_count} 个数据项: {item['title']}")
60
-
61
- return item
62
-
63
- def open_spider(self, spider):
64
- """
65
- 爬虫启动时调用。
66
-
67
- Args:
68
- spider: 爬虫实例
69
- """
70
- self.logger.info(f"管道已启动,准备处理爬虫 '{spider.name}' 的数据")
71
-
72
- def close_spider(self, spider):
73
- """
74
- 爬虫关闭时调用。
75
-
76
- Args:
77
- spider: 爬虫实例
78
- """
79
- self.logger.info(f"管道已关闭,共处理了 {self.item_count} 个数据项")
80
-
81
-
82
- # ======================== 使用说明 ========================
83
- #
84
- # 在 settings.py 中启用管道:
85
- # PIPELINES = [
86
- # 'test_project.pipelines.ExamplePipeline',
87
- # ]
88
- #
89
- # 您可以根据需要添加更多管道,例如:
90
- # 1. 数据验证管道
91
- # 2. 去重管道
92
- # 3. 数据存储管道(数据库、文件等)
93
- # 4. 数据转换管道
94
- #
95
- # 每个管道都应该实现 process_item 方法,
96
- # 可选实现 open_spider 和 close_spider 方法。
97
- # ======================== 使用说明 ========================
@@ -1,170 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- test_project 项目配置文件(分布式版)
4
- =============================
5
- 基于 Crawlo 框架的分布式爬虫项目配置。
6
- 适合大规模数据采集和多节点部署。
7
- """
8
-
9
- import os
10
-
11
- # ============================== 项目基本信息 ==============================
12
- PROJECT_NAME = 'test_project'
13
-
14
- # ============================== 运行模式 ==============================
15
- RUN_MODE = 'distributed'
16
-
17
- # ============================== 并发配置 ==============================
18
- CONCURRENCY = 16
19
- MAX_RUNNING_SPIDERS = 5
20
- DOWNLOAD_DELAY = 1.0
21
-
22
- # ============================== 下载器配置 ==============================
23
- # 可选下载器:
24
- # DOWNLOADER = 'crawlo.downloader.aiohttp_downloader.AioHttpDownloader'
25
- # DOWNLOADER = 'crawlo.downloader.httpx_downloader.HttpXDownloader'
26
- # DOWNLOADER = 'crawlo.downloader.cffi_downloader.CurlCffiDownloader'
27
- DOWNLOADER = 'crawlo.downloader.aiohttp_downloader.AioHttpDownloader'
28
-
29
- # ============================== 队列配置 ==============================
30
- QUEUE_TYPE = 'redis'
31
- # 当使用Redis队列时,可自定义队列名称
32
- # 队列名称遵循统一命名规范: crawlo:{PROJECT_NAME}:queue:requests
33
- # SCHEDULER_QUEUE_NAME = f'crawlo:{PROJECT_NAME}:queue:requests'
34
-
35
- # ============================== 去重过滤器 ==============================
36
- FILTER_CLASS = 'crawlo.filters.aioredis_filter.AioRedisFilter'
37
-
38
- # ============================== 默认去重管道 ==============================
39
- DEFAULT_DEDUP_PIPELINE = 'crawlo.pipelines.redis_dedup_pipeline.RedisDedupPipeline'
40
-
41
- # ============================== 爬虫模块配置 ==============================
42
- SPIDER_MODULES = ['test_project.spiders']
43
-
44
- # ============================== 中间件 ==============================
45
- # MIDDLEWARES = [
46
- # 'crawlo.middleware.simple_proxy.SimpleProxyMiddleware',
47
- # ]
48
-
49
- # ============================== 默认请求头配置 ==============================
50
- # 为DefaultHeaderMiddleware配置默认请求头
51
- DEFAULT_REQUEST_HEADERS = {
52
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
53
- 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
54
- 'Accept-Encoding': 'gzip, deflate, br',
55
- }
56
-
57
- # ============================== 允许的域名 ==============================
58
- # 为OffsiteMiddleware配置允许的域名
59
- # ALLOWED_DOMAINS = ['example.com']
60
-
61
- # ============================== 数据管道 ==============================
62
- # PIPELINES = [
63
- # 'crawlo.pipelines.mysql_pipeline.AsyncmyMySQLPipeline', # MySQL 存储(使用asyncmy异步库)
64
- # ]
65
-
66
- # ============================== 扩展组件 ==============================
67
- # EXTENSIONS = [
68
- # 'crawlo.extension.log_interval.LogIntervalExtension',
69
- # 'crawlo.extension.log_stats.LogStats',
70
- # 'crawlo.extension.logging_extension.CustomLoggerExtension',
71
- # ]
72
-
73
- # ============================== 日志配置 ==============================
74
- LOG_LEVEL = 'INFO'
75
- LOG_FILE = 'logs/test_project.log'
76
- LOG_ENCODING = 'utf-8' # 明确指定日志文件编码
77
- STATS_DUMP = True
78
-
79
- # ============================== 输出配置 ==============================
80
- OUTPUT_DIR = 'output'
81
-
82
- # ============================== Redis配置 ==============================
83
- REDIS_HOST = os.getenv('REDIS_HOST', '127.0.0.1')
84
- REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))
85
- REDIS_PASSWORD = os.getenv('REDIS_PASSWORD', '')
86
- REDIS_DB = int(os.getenv('REDIS_DB', 0))
87
-
88
- # 根据是否有密码生成 URL
89
- if REDIS_PASSWORD:
90
- REDIS_URL = f'redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'
91
- else:
92
- REDIS_URL = f'redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}'
93
-
94
- # ============================== MySQL配置 ==============================
95
- MYSQL_HOST = os.getenv('MYSQL_HOST', '127.0.0.1')
96
- MYSQL_PORT = int(os.getenv('MYSQL_PORT', 3306))
97
- MYSQL_USER = os.getenv('MYSQL_USER', 'root')
98
- MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', '123456')
99
- MYSQL_DB = os.getenv('MYSQL_DB', 'test_project')
100
- MYSQL_TABLE = 'test_project_data'
101
- MYSQL_BATCH_SIZE = 100
102
- MYSQL_USE_BATCH = True # 是否启用批量插入
103
-
104
- # ============================== MongoDB配置 ==============================
105
- MONGO_URI = os.getenv('MONGO_URI', 'mongodb://localhost:27017')
106
- MONGO_DATABASE = 'test_project_db'
107
- MONGO_COLLECTION = 'test_project_items'
108
- MONGO_MAX_POOL_SIZE = 200
109
- MONGO_MIN_POOL_SIZE = 20
110
- MONGO_BATCH_SIZE = 100 # 批量插入条数
111
- MONGO_USE_BATCH = True # 是否启用批量插入
112
-
113
- # ============================== 代理配置 ==============================
114
- # 代理功能默认不启用,如需使用请在项目配置文件中启用并配置相关参数
115
- PROXY_ENABLED = False # 是否启用代理
116
-
117
- # 简化版代理配置(适用于SimpleProxyMiddleware)
118
- PROXY_LIST = [] # 代理列表,例如: ["http://proxy1:8080", "http://proxy2:8080"]
119
-
120
- # 高级代理配置(适用于ProxyMiddleware)
121
- PROXY_API_URL = "" # 代理获取接口(请替换为真实地址)
122
-
123
- # 代理提取方式(支持字段路径或函数)
124
- # 示例: "proxy" 适用于 {"proxy": "http://1.1.1.1:8080"}
125
- # 示例: "data.proxy" 适用于 {"data": {"proxy": "http://1.1.1.1:8080"}}
126
- PROXY_EXTRACTOR = "proxy"
127
-
128
- # 代理刷新控制
129
- PROXY_REFRESH_INTERVAL = 60 # 代理刷新间隔(秒)
130
- PROXY_API_TIMEOUT = 10 # 请求代理 API 超时时间
131
-
132
- # ============================== Curl-Cffi 特有配置 ==============================
133
- # 浏览器指纹模拟(仅 CurlCffi 下载器有效)
134
- CURL_BROWSER_TYPE = "chrome" # 可选: chrome, edge, safari, firefox 或版本如 chrome136
135
-
136
- # 自定义浏览器版本映射(可覆盖默认行为)
137
- CURL_BROWSER_VERSION_MAP = {
138
- "chrome": "chrome136",
139
- "edge": "edge101",
140
- "safari": "safari184",
141
- "firefox": "firefox135",
142
- }
143
-
144
- # ============================== 下载器优化配置 ==============================
145
- # 下载器健康检查
146
- DOWNLOADER_HEALTH_CHECK = True # 是否启用下载器健康检查
147
- HEALTH_CHECK_INTERVAL = 60 # 健康检查间隔(秒)
148
-
149
- # 请求统计配置
150
- REQUEST_STATS_ENABLED = True # 是否启用请求统计
151
- STATS_RESET_ON_START = False # 启动时是否重置统计
152
-
153
- # HttpX 下载器专用配置
154
- HTTPX_HTTP2 = True # 是否启用HTTP/2支持
155
- HTTPX_FOLLOW_REDIRECTS = True # 是否自动跟随重定向
156
-
157
- # AioHttp 下载器专用配置
158
- AIOHTTP_AUTO_DECOMPRESS = True # 是否自动解压响应
159
- AIOHTTP_FORCE_CLOSE = False # 是否强制关闭连接
160
-
161
- # 通用优化配置
162
- CONNECTION_TTL_DNS_CACHE = 300 # DNS缓存TTL(秒)
163
- CONNECTION_KEEPALIVE_TIMEOUT = 15 # Keep-Alive超时(秒)
164
-
165
- # ============================== 内存监控配置 ==============================
166
- # 内存监控扩展默认不启用,如需使用请在项目配置文件中启用
167
- MEMORY_MONITOR_ENABLED = False # 是否启用内存监控
168
- MEMORY_MONITOR_INTERVAL = 60 # 内存监控检查间隔(秒)
169
- MEMORY_WARNING_THRESHOLD = 80.0 # 内存使用率警告阈值(百分比)
170
- MEMORY_CRITICAL_THRESHOLD = 90.0 # 内存使用率严重阈值(百分比)
@@ -1,10 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- test_project.spiders
4
- ========================
5
- 存放所有的爬虫。
6
- """
7
-
8
- # 自动导入所有爬虫以确保它们被注册
9
- # 示例:
10
- # from .YourSpider import YourSpider
@@ -1,144 +0,0 @@
1
- # -*- coding: UTF-8 -*-
2
- """
3
- test_project.spiders.of_week_dis
4
- =======================================
5
- 由 `crawlo genspider` 命令生成的爬虫。
6
- 基于 Crawlo 框架,支持异步并发、分布式爬取等功能。
7
-
8
- 使用示例:
9
- crawlo crawl of_week_dis
10
- """
11
-
12
- from crawlo.spider import Spider
13
- from crawlo import Request
14
- from ..items import ExampleItem
15
-
16
-
17
- class OfweekdisSpider(Spider):
18
- """
19
- 爬虫:of_week_dis
20
-
21
- 功能说明:
22
- - 支持并发爬取
23
- - 自动去重过滤
24
- - 错误重试机制
25
- - 数据管道处理
26
- """
27
- name = 'of_week_dis'
28
- allowed_domains = ['ee.ofweek.com']
29
- start_urls = ['https://ee.ofweek.com/']
30
-
31
- # 高级配置(可选)
32
- # custom_settings = {
33
- # 'DOWNLOAD_DELAY': 2.0,
34
- # 'CONCURRENCY': 4,
35
- # 'RETRY_HTTP_CODES': [500, 502, 503, 504, 408, 429],
36
- # 'ALLOWED_RESPONSE_CODES': [200, 301, 302], # 只允许特定状态码
37
- # 'DENIED_RESPONSE_CODES': [403, 404], # 拒绝特定状态码
38
- # }
39
-
40
- def start_requests(self):
41
- """
42
- 生成初始请求。
43
-
44
- 支持自定义请求头、代理、优先级等。
45
- """
46
- headers = {
47
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
48
- 'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
49
- }
50
-
51
- for url in self.start_urls:
52
- yield Request(
53
- url=url,
54
- callback=self.parse,
55
- headers=headers,
56
- # meta={'proxy': 'http://proxy.example.com:8080'}, # 自定义代理
57
- # priority=10, # 请求优先级(数字越大优先级越高)
58
- )
59
-
60
- def parse(self, response):
61
- """
62
- 解析响应的主方法。
63
-
64
- Args:
65
- response: 响应对象,包含页面内容和元数据
66
-
67
- Yields:
68
- Request: 新的请求对象(用于深度爬取)
69
- Item: 数据项对象(用于数据存储)
70
- """
71
- self.logger.info(f'正在解析页面: {response.url}')
72
-
73
- # ================== 数据提取示例 ==================
74
-
75
- # 提取数据并创建 Item
76
- # item = Item()
77
- # item['title'] = response.xpath('//title/text()').get(default='')
78
- # item['url'] = response.url
79
- # item['content'] = response.xpath('//div[@class="content"]//text()').getall()
80
- # yield item
81
-
82
- # 直接返回字典(简单数据)
83
- yield {
84
- 'title': response.xpath('//title/text()').get(default=''),
85
- 'url': response.url,
86
- 'status_code': response.status_code,
87
- # 'description': response.xpath('//meta[@name="description"]/@content').get(),
88
- # 'keywords': response.xpath('//meta[@name="keywords"]/@content').get(),
89
- }
90
-
91
- # ================== 链接提取示例 ==================
92
-
93
- # 提取并跟进链接
94
- # links = response.xpath('//a/@href').getall()
95
- # for link in links:
96
- # # 过滤有效链接
97
- # if link and not link.startswith(('javascript:', 'mailto:', '#')):
98
- # yield response.follow(
99
- # link,
100
- # callback=self.parse_detail, # 或者 self.parse 继续递归
101
- # meta={'parent_url': response.url} # 传递父页面信息
102
- # )
103
-
104
- # 用 CSS 选择器提取链接
105
- # for link in response.css('a.item-link::attr(href)').getall():
106
- # yield response.follow(link, callback=self.parse_detail)
107
-
108
- # ================== 分页处理示例 ==================
109
-
110
- # 处理分页
111
- # next_page = response.xpath('//a[@class="next"]/@href').get()
112
- # if next_page:
113
- # yield response.follow(next_page, callback=self.parse)
114
-
115
- # 数字分页
116
- # current_page = int(response.meta.get('page', 1))
117
- # max_pages = 100 # 设置最大页数
118
- # if current_page < max_pages:
119
- # next_url = f'https://ee.ofweek.com/page/{current_page + 1}'
120
- # yield Request(
121
- # url=next_url,
122
- # callback=self.parse,
123
- # meta={'page': current_page + 1}
124
- # )
125
-
126
- def parse_detail(self, response):
127
- """
128
- 解析详情页面的方法(可选)。
129
-
130
- 用于处理从列表页跳转而来的详情页。
131
- """
132
- self.logger.info(f'正在解析详情页: {response.url}')
133
-
134
- # parent_url = response.meta.get('parent_url', '')
135
- #
136
- # yield {
137
- # 'title': response.xpath('//h1/text()').get(default=''),
138
- # 'content': '\n'.join(response.xpath('//div[@class="content"]//text()').getall()),
139
- # 'url': response.url,
140
- # 'parent_url': parent_url,
141
- # 'publish_time': response.xpath('//time/@datetime').get(),
142
- # }
143
-
144
- pass
tests/simple_log_test.py DELETED
@@ -1,58 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: UTF-8 -*-
3
- """
4
- 简单的日志系统测试
5
- """
6
- import sys
7
- import os
8
- sys.path.insert(0, '/')
9
-
10
- # 确保日志目录存在
11
- os.makedirs('/examples/ofweek_standalone/logs', exist_ok=True)
12
-
13
- # 测试日志系统
14
- from crawlo.utils.log import LoggerManager, get_logger
15
-
16
- print("=== 简单日志系统测试 ===")
17
-
18
- # 1. 直接配置日志系统
19
- print("1. 配置日志系统...")
20
- LoggerManager.configure(
21
- LOG_LEVEL='INFO',
22
- LOG_FILE='/Users/oscar/projects/Crawlo/examples/ofweek_standalone/logs/simple_test.log'
23
- )
24
-
25
- # 2. 创建logger
26
- print("2. 创建logger...")
27
- logger = get_logger('test.logger')
28
- print(f" Logger: {logger}")
29
- print(f" Handlers: {len(logger.handlers)}")
30
-
31
- for i, handler in enumerate(logger.handlers):
32
- handler_type = type(handler).__name__
33
- print(f" Handler {i}: {handler_type}")
34
- if hasattr(handler, 'baseFilename'):
35
- print(f" File: {handler.baseFilename}")
36
-
37
- # 3. 测试日志输出
38
- print("3. 测试日志输出...")
39
- logger.info("这是一条测试INFO日志")
40
- logger.debug("这是一条测试DEBUG日志")
41
- logger.warning("这是一条测试WARNING日志")
42
-
43
- print("4. 检查日志文件...")
44
- log_file = '/Users/oscar/projects/Crawlo/examples/ofweek_standalone/logs/simple_test.log'
45
- if os.path.exists(log_file):
46
- print(f" 日志文件存在: {log_file}")
47
- with open(log_file, 'r', encoding='utf-8') as f:
48
- content = f.read()
49
- print(f" 文件内容长度: {len(content)} 字符")
50
- if content:
51
- print(" 文件内容:")
52
- print(content)
53
- else:
54
- print(" 文件为空")
55
- else:
56
- print(f" 日志文件不存在: {log_file}")
57
-
58
- print("=== 测试完成 ===")
tests/simple_test.py DELETED
@@ -1,48 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- 简化的框架测试
5
- """
6
- import os
7
- import sys
8
- sys.path.insert(0, '/')
9
-
10
- # 设置基本配置
11
- test_log_file = '/Users/oscar/projects/Crawlo/simple_test.log'
12
- if os.path.exists(test_log_file):
13
- os.remove(test_log_file)
14
-
15
- # 最简单的测试
16
- try:
17
- from crawlo.utils.log import LoggerManager
18
-
19
- print("配置日志系统...")
20
- LoggerManager.configure(
21
- LOG_LEVEL='INFO',
22
- LOG_FILE=test_log_file
23
- )
24
-
25
- from crawlo.utils.log import get_logger
26
- logger = get_logger('test.simple')
27
-
28
- print("测试日志输出...")
29
- logger.info("这是一条测试信息")
30
- logger.info("Crawlo框架初始化完成")
31
- logger.info("Crawlo Framework Started 1.3.3")
32
-
33
- print("检查日志文件...")
34
- if os.path.exists(test_log_file):
35
- with open(test_log_file, 'r', encoding='utf-8') as f:
36
- content = f.read()
37
- print(f"日志文件内容: {len(content)} 字符")
38
- print("内容:")
39
- print(content)
40
- else:
41
- print("日志文件未创建")
42
-
43
- except Exception as e:
44
- print(f"错误: {e}")
45
- import traceback
46
- traceback.print_exc()
47
-
48
- print("测试完成")