crawlo 1.1.1__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.
- crawlo/__init__.py +2 -1
- crawlo/__version__.py +1 -1
- crawlo/commands/genspider.py +68 -42
- crawlo/commands/list.py +102 -93
- crawlo/commands/startproject.py +89 -4
- crawlo/commands/utils.py +187 -0
- crawlo/config.py +280 -0
- crawlo/core/engine.py +16 -3
- crawlo/core/enhanced_engine.py +190 -0
- crawlo/core/scheduler.py +113 -8
- crawlo/crawler.py +840 -307
- crawlo/downloader/__init__.py +181 -17
- crawlo/downloader/aiohttp_downloader.py +15 -2
- crawlo/downloader/cffi_downloader.py +11 -1
- crawlo/downloader/httpx_downloader.py +14 -3
- crawlo/filters/__init__.py +122 -5
- crawlo/filters/aioredis_filter.py +128 -36
- crawlo/filters/memory_filter.py +99 -32
- crawlo/middleware/proxy.py +11 -8
- crawlo/middleware/retry.py +40 -5
- crawlo/mode_manager.py +201 -0
- crawlo/network/__init__.py +17 -3
- crawlo/network/request.py +118 -10
- crawlo/network/response.py +131 -28
- crawlo/pipelines/__init__.py +1 -1
- crawlo/pipelines/csv_pipeline.py +317 -0
- crawlo/pipelines/json_pipeline.py +219 -0
- crawlo/queue/__init__.py +0 -0
- crawlo/queue/pqueue.py +37 -0
- crawlo/queue/queue_manager.py +304 -0
- crawlo/queue/redis_priority_queue.py +192 -0
- crawlo/settings/default_settings.py +68 -9
- crawlo/spider/__init__.py +576 -66
- crawlo/task_manager.py +4 -1
- crawlo/templates/project/middlewares.py.tmpl +56 -45
- crawlo/templates/project/pipelines.py.tmpl +308 -36
- crawlo/templates/project/run.py.tmpl +239 -0
- crawlo/templates/project/settings.py.tmpl +211 -17
- crawlo/templates/spider/spider.py.tmpl +153 -7
- crawlo/utils/controlled_spider_mixin.py +336 -0
- crawlo/utils/large_scale_config.py +287 -0
- crawlo/utils/large_scale_helper.py +344 -0
- crawlo/utils/queue_helper.py +176 -0
- crawlo/utils/request_serializer.py +220 -0
- crawlo-1.1.2.dist-info/METADATA +567 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/RECORD +54 -46
- tests/test_final_validation.py +154 -0
- tests/test_redis_config.py +29 -0
- tests/test_redis_queue.py +225 -0
- tests/test_request_serialization.py +71 -0
- tests/test_scheduler.py +242 -0
- crawlo/pipelines/mysql_batch_pipline.py +0 -273
- crawlo/utils/pqueue.py +0 -174
- crawlo-1.1.1.dist-info/METADATA +0 -220
- examples/baidu_spider/__init__.py +0 -7
- examples/baidu_spider/demo.py +0 -94
- examples/baidu_spider/items.py +0 -46
- examples/baidu_spider/middleware.py +0 -49
- examples/baidu_spider/pipeline.py +0 -55
- examples/baidu_spider/run.py +0 -27
- examples/baidu_spider/settings.py +0 -121
- examples/baidu_spider/spiders/__init__.py +0 -7
- examples/baidu_spider/spiders/bai_du.py +0 -61
- examples/baidu_spider/spiders/miit.py +0 -159
- examples/baidu_spider/spiders/sina.py +0 -79
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/WHEEL +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/entry_points.txt +0 -0
- {crawlo-1.1.1.dist-info → crawlo-1.1.2.dist-info}/top_level.txt +0 -0
crawlo/task_manager.py
CHANGED
|
@@ -11,7 +11,10 @@ class TaskManager:
|
|
|
11
11
|
self.current_task: Final[Set] = set()
|
|
12
12
|
self.semaphore: Semaphore = Semaphore(total_concurrency)
|
|
13
13
|
|
|
14
|
-
def create_task(self, coroutine) -> Task:
|
|
14
|
+
async def create_task(self, coroutine) -> Task:
|
|
15
|
+
# 等待信号量,控制并发数
|
|
16
|
+
await self.semaphore.acquire()
|
|
17
|
+
|
|
15
18
|
task = asyncio.create_task(coroutine)
|
|
16
19
|
self.current_task.add(task)
|
|
17
20
|
|
|
@@ -5,72 +5,83 @@
|
|
|
5
5
|
自定义中间件,用于在请求/响应/异常处理过程中插入自定义逻辑。
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
import random
|
|
9
|
+
from crawlo import Request, Response
|
|
10
|
+
from crawlo.utils.log import get_logger
|
|
11
|
+
from crawlo.exceptions import IgnoreRequest
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class RandomUserAgentMiddleware:
|
|
15
|
+
"""随机 User-Agent 中间件。"""
|
|
16
|
+
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
19
|
+
self.user_agents = [
|
|
20
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
|
|
21
|
+
'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',
|
|
22
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
23
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:135.0) Gecko/20100101 Firefox/135.0',
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
def process_request(self, request, spider):
|
|
27
|
+
if 'User-Agent' not in request.headers:
|
|
28
|
+
ua = random.choice(self.user_agents)
|
|
29
|
+
request.headers['User-Agent'] = ua
|
|
30
|
+
return None
|
|
31
|
+
|
|
32
|
+
|
|
9
33
|
class CustomDownloaderMiddleware:
|
|
10
|
-
"""
|
|
11
|
-
|
|
12
|
-
|
|
34
|
+
"""自定义下载器中间件示例。"""
|
|
35
|
+
|
|
36
|
+
def __init__(self):
|
|
37
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
13
38
|
|
|
14
39
|
def process_request(self, request, spider):
|
|
15
|
-
"""
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
#
|
|
19
|
-
#
|
|
20
|
-
|
|
21
|
-
# return Response(...) # 返回一个响应,停止下载
|
|
22
|
-
pass
|
|
40
|
+
"""在请求被下载器执行前调用。"""
|
|
41
|
+
# 示例:添加自定义请求头
|
|
42
|
+
# request.headers['Custom-Header'] = 'Custom-Value'
|
|
43
|
+
# 示例:设置代理
|
|
44
|
+
# request.meta['proxy'] = 'http://proxy.example.com:8080'
|
|
45
|
+
return None
|
|
23
46
|
|
|
24
47
|
def process_response(self, request, response, spider):
|
|
25
|
-
"""
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
pass
|
|
48
|
+
"""在响应被 Spider 处理前调用。"""
|
|
49
|
+
# 示例:检查响应状态
|
|
50
|
+
if response.status_code == 403:
|
|
51
|
+
self.logger.warning(f"访问被拒绝: {request.url}")
|
|
52
|
+
return response
|
|
31
53
|
|
|
32
54
|
def process_exception(self, request, exception, spider):
|
|
33
|
-
"""
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
# return None # 继续抛出异常
|
|
37
|
-
# return request # 重试
|
|
38
|
-
# return Response(...) # 返回一个响应
|
|
39
|
-
pass
|
|
55
|
+
"""在下载或处理过程中发生异常时调用。"""
|
|
56
|
+
self.logger.error(f"请求异常: {request.url} - {exception}")
|
|
57
|
+
return None
|
|
40
58
|
|
|
41
59
|
|
|
42
|
-
# 示例:Spider 中间件
|
|
43
60
|
class CustomSpiderMiddleware:
|
|
44
61
|
"""
|
|
45
|
-
|
|
62
|
+
Spider 中间件示例。
|
|
46
63
|
"""
|
|
47
64
|
|
|
65
|
+
def __init__(self):
|
|
66
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
67
|
+
|
|
48
68
|
def process_spider_input(self, response, spider):
|
|
49
|
-
"""
|
|
50
|
-
在 Spider 的 parse 方法被调用前调用。
|
|
51
|
-
"""
|
|
69
|
+
"""在 Spider 的 parse 方法被调用前调用。"""
|
|
52
70
|
# 可以用来验证响应
|
|
53
71
|
pass
|
|
54
72
|
|
|
55
73
|
def process_spider_output(self, response, result, spider):
|
|
56
|
-
"""
|
|
57
|
-
在 Spider 的 parse 方法返回结果后调用。
|
|
58
|
-
"""
|
|
74
|
+
"""在 Spider 的 parse 方法返回结果后调用。"""
|
|
59
75
|
# 可以用来过滤或修改结果
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
pass
|
|
76
|
+
for item in result:
|
|
77
|
+
yield item
|
|
63
78
|
|
|
64
79
|
def process_spider_exception(self, response, exception, spider):
|
|
65
|
-
"""
|
|
66
|
-
|
|
67
|
-
"""
|
|
80
|
+
"""在 Spider 的 parse 方法抛出异常时调用。"""
|
|
81
|
+
self.logger.error(f"Spider 异常: {response.url} - {exception}")
|
|
68
82
|
pass
|
|
69
83
|
|
|
70
84
|
def process_start_requests(self, start_requests, spider):
|
|
71
|
-
"""
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
# for request in start_requests:
|
|
75
|
-
# yield request
|
|
76
|
-
pass
|
|
85
|
+
"""在 Spider 的 start_requests 生成器被消费时调用。"""
|
|
86
|
+
for request in start_requests:
|
|
87
|
+
yield request
|
|
@@ -4,61 +4,333 @@
|
|
|
4
4
|
==========================
|
|
5
5
|
数据管道,用于处理 Spider 返回的 Item。
|
|
6
6
|
例如:清理、验证、去重、保存到数据库等。
|
|
7
|
+
|
|
8
|
+
支持异步并发处理和多种存储后端。
|
|
7
9
|
"""
|
|
8
10
|
|
|
11
|
+
import json
|
|
12
|
+
import asyncio
|
|
13
|
+
from typing import Dict, Any
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from crawlo.exceptions import DropItem
|
|
16
|
+
from crawlo.utils.log import get_logger
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ValidationPipeline:
|
|
20
|
+
"""
|
|
21
|
+
数据验证管道。
|
|
22
|
+
|
|
23
|
+
验证必要字段是否存在,过滤无效数据。
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self):
|
|
27
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
28
|
+
# 必要字段列表(根据实际需要修改)
|
|
29
|
+
self.required_fields = ['title', 'url']
|
|
30
|
+
|
|
31
|
+
def process_item(self, item, spider):
|
|
32
|
+
"""验证数据项。"""
|
|
33
|
+
# 检查必要字段
|
|
34
|
+
for field in self.required_fields:
|
|
35
|
+
if not item.get(field):
|
|
36
|
+
raise DropItem(f"缺少必要字段: {field}")
|
|
37
|
+
|
|
38
|
+
# 数据清理
|
|
39
|
+
if 'title' in item:
|
|
40
|
+
item['title'] = str(item['title']).strip()
|
|
41
|
+
|
|
42
|
+
# 添加时间戳
|
|
43
|
+
item['crawled_at'] = datetime.now().isoformat()
|
|
44
|
+
|
|
45
|
+
self.logger.debug(f"数据验证通过: {item.get('url', 'Unknown URL')}")
|
|
46
|
+
return item
|
|
47
|
+
|
|
48
|
+
|
|
9
49
|
class PrintItemPipeline:
|
|
10
50
|
"""
|
|
11
|
-
|
|
51
|
+
简单的打印管道,用于调试。
|
|
12
52
|
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self):
|
|
55
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
56
|
+
self.item_count = 0
|
|
13
57
|
|
|
14
58
|
def process_item(self, item, spider):
|
|
15
|
-
|
|
59
|
+
"""打印数据项。"""
|
|
60
|
+
self.item_count += 1
|
|
61
|
+
self.logger.info(f"[第{self.item_count}个数据] {json.dumps(dict(item), ensure_ascii=False, indent=2)}")
|
|
16
62
|
return item
|
|
17
63
|
|
|
18
64
|
|
|
19
65
|
class DuplicatesPipeline:
|
|
20
66
|
"""
|
|
21
|
-
|
|
67
|
+
去重管道。
|
|
68
|
+
|
|
69
|
+
基于指定字段进行去重,防止重复数据。
|
|
22
70
|
"""
|
|
71
|
+
|
|
23
72
|
def __init__(self):
|
|
73
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
24
74
|
self.seen = set()
|
|
75
|
+
# 去重字段(可以是 'url', 'id', 或其他唯一标识)
|
|
76
|
+
self.duplicate_field = 'url'
|
|
77
|
+
self.drop_count = 0
|
|
25
78
|
|
|
26
79
|
def process_item(self, item, spider):
|
|
27
|
-
|
|
80
|
+
"""检查并去除重复数据。"""
|
|
81
|
+
identifier = item.get(self.duplicate_field)
|
|
82
|
+
|
|
83
|
+
if not identifier:
|
|
84
|
+
self.logger.warning(f"数据项缺少去重字段 '{self.duplicate_field}',跳过去重检查")
|
|
85
|
+
return item
|
|
86
|
+
|
|
28
87
|
if identifier in self.seen:
|
|
29
|
-
|
|
30
|
-
|
|
88
|
+
self.drop_count += 1
|
|
89
|
+
self.logger.debug(f"发现重复数据: {identifier} (已过滤{self.drop_count}个)")
|
|
90
|
+
raise DropItem(f"重复数据: {identifier}")
|
|
91
|
+
|
|
31
92
|
self.seen.add(identifier)
|
|
32
93
|
return item
|
|
94
|
+
|
|
95
|
+
def close_spider(self, spider):
|
|
96
|
+
"""爬虫结束时输出统计信息。"""
|
|
97
|
+
self.logger.info(f"去重管道统计: 已过滤{self.drop_count}个重复数据,唯一数据{len(self.seen)}个")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class JsonFilesPipeline:
|
|
101
|
+
"""
|
|
102
|
+
JSON 文件存储管道。
|
|
103
|
+
|
|
104
|
+
将每个数据项保存为单独的 JSON 文件。
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(self, output_dir='output'):
|
|
108
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
109
|
+
self.output_dir = output_dir
|
|
110
|
+
self.file_count = 0
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def from_crawler(cls, crawler):
|
|
114
|
+
"""从爬虫配置创建管道实例。"""
|
|
115
|
+
output_dir = crawler.settings.get('JSON_OUTPUT_DIR', 'output')
|
|
116
|
+
return cls(output_dir=output_dir)
|
|
117
|
+
|
|
118
|
+
def open_spider(self, spider):
|
|
119
|
+
"""爬虫启动时创建输出目录。"""
|
|
120
|
+
import os
|
|
121
|
+
os.makedirs(self.output_dir, exist_ok=True)
|
|
122
|
+
self.logger.info(f"JSON 文件将保存到: {self.output_dir}")
|
|
123
|
+
|
|
124
|
+
def process_item(self, item, spider):
|
|
125
|
+
"""将数据项保存为 JSON 文件。"""
|
|
126
|
+
self.file_count += 1
|
|
127
|
+
filename = f"{spider.name}_{self.file_count:06d}.json"
|
|
128
|
+
filepath = f"{self.output_dir}/{filename}"
|
|
129
|
+
|
|
130
|
+
with open(filepath, 'w', encoding='utf-8') as f:
|
|
131
|
+
json.dump(dict(item), f, ensure_ascii=False, indent=2)
|
|
132
|
+
|
|
133
|
+
self.logger.debug(f"已保存: {filepath}")
|
|
134
|
+
return item
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class DatabasePipeline:
|
|
138
|
+
"""
|
|
139
|
+
数据库存储管道示例。
|
|
140
|
+
|
|
141
|
+
支持 MySQL 和 MongoDB,可根据需要选择。
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
def __init__(self, database_type='mysql'):
|
|
145
|
+
self.logger = get_logger(self.__class__.__name__)
|
|
146
|
+
self.database_type = database_type
|
|
147
|
+
self.connection = None
|
|
148
|
+
self.batch_items = []
|
|
149
|
+
self.batch_size = 100 # 批量写入大小
|
|
150
|
+
|
|
151
|
+
@classmethod
|
|
152
|
+
def from_crawler(cls, crawler):
|
|
153
|
+
"""从爬虫配置创建管道实例。"""
|
|
154
|
+
db_type = crawler.settings.get('DATABASE_TYPE', 'mysql')
|
|
155
|
+
return cls(database_type=db_type)
|
|
156
|
+
|
|
157
|
+
async def open_spider(self, spider):
|
|
158
|
+
"""爬虫启动时连接数据库。"""
|
|
159
|
+
if self.database_type == 'mysql':
|
|
160
|
+
await self._connect_mysql(spider)
|
|
161
|
+
elif self.database_type == 'mongodb':
|
|
162
|
+
await self._connect_mongodb(spider)
|
|
163
|
+
else:
|
|
164
|
+
raise ValueError(f"不支持的数据库类型: {self.database_type}")
|
|
165
|
+
|
|
166
|
+
async def _connect_mysql(self, spider):
|
|
167
|
+
"""连接 MySQL 数据库。"""
|
|
168
|
+
try:
|
|
169
|
+
import aiomysql
|
|
170
|
+
|
|
171
|
+
settings = spider.crawler.settings
|
|
172
|
+
self.connection = await aiomysql.connect(
|
|
173
|
+
host=settings.get('MYSQL_HOST', '127.0.0.1'),
|
|
174
|
+
port=settings.get('MYSQL_PORT', 3306),
|
|
175
|
+
user=settings.get('MYSQL_USER', 'root'),
|
|
176
|
+
password=settings.get('MYSQL_PASSWORD', ''),
|
|
177
|
+
db=settings.get('MYSQL_DB', '{{project_name}}'),
|
|
178
|
+
charset='utf8mb4',
|
|
179
|
+
autocommit=True
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
# 创建表(如果不存在)
|
|
183
|
+
await self._create_mysql_table(spider)
|
|
184
|
+
self.logger.info("已连接到 MySQL 数据库")
|
|
185
|
+
|
|
186
|
+
except ImportError:
|
|
187
|
+
self.logger.error("缺少 aiomysql 依赖,请安装: pip install aiomysql")
|
|
188
|
+
raise
|
|
189
|
+
except Exception as e:
|
|
190
|
+
self.logger.error(f"MySQL 连接失败: {e}")
|
|
191
|
+
raise
|
|
192
|
+
|
|
193
|
+
async def _connect_mongodb(self, spider):
|
|
194
|
+
"""连接 MongoDB 数据库。"""
|
|
195
|
+
try:
|
|
196
|
+
from motor.motor_asyncio import AsyncIOMotorClient
|
|
197
|
+
|
|
198
|
+
settings = spider.crawler.settings
|
|
199
|
+
mongo_uri = settings.get('MONGO_URI', 'mongodb://localhost:27017')
|
|
200
|
+
|
|
201
|
+
self.connection = AsyncIOMotorClient(mongo_uri)
|
|
202
|
+
self.database = self.connection[settings.get('MONGO_DATABASE', '{{project_name}}_db')]
|
|
203
|
+
self.collection = self.database[settings.get('MONGO_COLLECTION', '{{project_name}}_items')]
|
|
204
|
+
|
|
205
|
+
self.logger.info("已连接到 MongoDB 数据库")
|
|
206
|
+
|
|
207
|
+
except ImportError:
|
|
208
|
+
self.logger.error("缺少 motor 依赖,请安装: pip install motor")
|
|
209
|
+
raise
|
|
210
|
+
except Exception as e:
|
|
211
|
+
self.logger.error(f"MongoDB 连接失败: {e}")
|
|
212
|
+
raise
|
|
213
|
+
|
|
214
|
+
async def _create_mysql_table(self, spider):
|
|
215
|
+
"""创建 MySQL 表结构。"""
|
|
216
|
+
table_name = spider.crawler.settings.get('MYSQL_TABLE', '{{project_name}}_data')
|
|
217
|
+
|
|
218
|
+
create_sql = f"""
|
|
219
|
+
CREATE TABLE IF NOT EXISTS `{table_name}` (
|
|
220
|
+
`id` bigint AUTO_INCREMENT PRIMARY KEY,
|
|
221
|
+
`title` varchar(500) DEFAULT NULL,
|
|
222
|
+
`url` varchar(1000) NOT NULL,
|
|
223
|
+
`content` text DEFAULT NULL,
|
|
224
|
+
`crawled_at` datetime DEFAULT CURRENT_TIMESTAMP,
|
|
225
|
+
`spider_name` varchar(100) DEFAULT NULL,
|
|
226
|
+
`extra_data` json DEFAULT NULL,
|
|
227
|
+
UNIQUE KEY `unique_url` (`url`(255)),
|
|
228
|
+
INDEX `idx_spider_name` (`spider_name`),
|
|
229
|
+
INDEX `idx_crawled_at` (`crawled_at`)
|
|
230
|
+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
async with self.connection.cursor() as cursor:
|
|
234
|
+
await cursor.execute(create_sql)
|
|
235
|
+
self.logger.info(f"表 '{table_name}' 准备就绪")
|
|
236
|
+
|
|
237
|
+
async def process_item(self, item, spider):
|
|
238
|
+
"""处理数据项(批量存储)。"""
|
|
239
|
+
self.batch_items.append(dict(item))
|
|
240
|
+
|
|
241
|
+
# 批量存储
|
|
242
|
+
if len(self.batch_items) >= self.batch_size:
|
|
243
|
+
await self._save_batch(spider)
|
|
244
|
+
|
|
245
|
+
return item
|
|
246
|
+
|
|
247
|
+
async def _save_batch(self, spider):
|
|
248
|
+
"""批量保存数据。"""
|
|
249
|
+
if not self.batch_items:
|
|
250
|
+
return
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
if self.database_type == 'mysql':
|
|
254
|
+
await self._save_to_mysql(spider)
|
|
255
|
+
elif self.database_type == 'mongodb':
|
|
256
|
+
await self._save_to_mongodb(spider)
|
|
257
|
+
|
|
258
|
+
self.logger.info(f"批量保存 {len(self.batch_items)} 条数据")
|
|
259
|
+
self.batch_items.clear()
|
|
260
|
+
|
|
261
|
+
except Exception as e:
|
|
262
|
+
self.logger.error(f"批量保存失败: {e}")
|
|
263
|
+
# 可以选择重试或记录失败数据
|
|
264
|
+
|
|
265
|
+
async def _save_to_mysql(self, spider):
|
|
266
|
+
"""保存到 MySQL。"""
|
|
267
|
+
table_name = spider.crawler.settings.get('MYSQL_TABLE', '{{project_name}}_data')
|
|
268
|
+
|
|
269
|
+
insert_sql = f"""
|
|
270
|
+
INSERT INTO `{table_name}`
|
|
271
|
+
(`title`, `url`, `content`, `spider_name`, `extra_data`)
|
|
272
|
+
VALUES (%s, %s, %s, %s, %s)
|
|
273
|
+
ON DUPLICATE KEY UPDATE
|
|
274
|
+
`title` = VALUES(`title`),
|
|
275
|
+
`content` = VALUES(`content`),
|
|
276
|
+
`crawled_at` = CURRENT_TIMESTAMP
|
|
277
|
+
"""
|
|
278
|
+
|
|
279
|
+
async with self.connection.cursor() as cursor:
|
|
280
|
+
batch_data = []
|
|
281
|
+
for item in self.batch_items:
|
|
282
|
+
# 提取标准字段
|
|
283
|
+
title = item.get('title', '')[:500] # 限制长度
|
|
284
|
+
url = item.get('url', '')
|
|
285
|
+
content = item.get('content', '')
|
|
286
|
+
|
|
287
|
+
# 其他字段作为 JSON 存储
|
|
288
|
+
extra_fields = {k: v for k, v in item.items()
|
|
289
|
+
if k not in ['title', 'url', 'content']}
|
|
290
|
+
extra_data = json.dumps(extra_fields, ensure_ascii=False) if extra_fields else None
|
|
291
|
+
|
|
292
|
+
batch_data.append((title, url, content, spider.name, extra_data))
|
|
293
|
+
|
|
294
|
+
await cursor.executemany(insert_sql, batch_data)
|
|
295
|
+
|
|
296
|
+
async def _save_to_mongodb(self, spider):
|
|
297
|
+
"""保存到 MongoDB。"""
|
|
298
|
+
# 为每个数据项添加 spider_name
|
|
299
|
+
for item in self.batch_items:
|
|
300
|
+
item['spider_name'] = spider.name
|
|
301
|
+
|
|
302
|
+
# 批量插入
|
|
303
|
+
await self.collection.insert_many(self.batch_items)
|
|
304
|
+
|
|
305
|
+
async def close_spider(self, spider):
|
|
306
|
+
"""爬虫结束时保存剩余数据并关闭连接。"""
|
|
307
|
+
# 保存剩余数据
|
|
308
|
+
if self.batch_items:
|
|
309
|
+
await self._save_batch(spider)
|
|
310
|
+
|
|
311
|
+
# 关闭连接
|
|
312
|
+
if self.connection:
|
|
313
|
+
if self.database_type == 'mysql':
|
|
314
|
+
self.connection.close()
|
|
315
|
+
elif self.database_type == 'mongodb':
|
|
316
|
+
self.connection.close()
|
|
317
|
+
|
|
318
|
+
self.logger.info("数据库连接已关闭")
|
|
33
319
|
|
|
34
320
|
|
|
35
|
-
#
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
#
|
|
40
|
-
#
|
|
41
|
-
#
|
|
42
|
-
#
|
|
43
|
-
#
|
|
44
|
-
#
|
|
45
|
-
#
|
|
46
|
-
#
|
|
47
|
-
#
|
|
48
|
-
#
|
|
49
|
-
#
|
|
50
|
-
#
|
|
51
|
-
# mysql_password=settings.get('MYSQL_PASSWORD'),
|
|
52
|
-
# mysql_db=settings.get('MYSQL_DB')
|
|
53
|
-
# )
|
|
54
|
-
#
|
|
55
|
-
# def open_spider(self, spider):
|
|
56
|
-
# self.connection = pymysql.connect(...)
|
|
57
|
-
#
|
|
58
|
-
# def close_spider(self, spider):
|
|
59
|
-
# if self.connection:
|
|
60
|
-
# self.connection.close()
|
|
61
|
-
#
|
|
62
|
-
# def process_item(self, item, spider):
|
|
63
|
-
# # 执行 SQL 插入
|
|
64
|
-
# return item
|
|
321
|
+
# ======================== 使用说明 ========================
|
|
322
|
+
#
|
|
323
|
+
# 在 settings.py 中启用管道:
|
|
324
|
+
# PIPELINES = [
|
|
325
|
+
# '{{project_name}}.pipelines.ValidationPipeline', # 数据验证
|
|
326
|
+
# '{{project_name}}.pipelines.DuplicatesPipeline', # 去重过滤
|
|
327
|
+
# '{{project_name}}.pipelines.PrintItemPipeline', # 打印输出(调试)
|
|
328
|
+
# '{{project_name}}.pipelines.JsonFilesPipeline', # JSON 文件存储
|
|
329
|
+
# '{{project_name}}.pipelines.DatabasePipeline', # 数据库存储
|
|
330
|
+
# ]
|
|
331
|
+
#
|
|
332
|
+
# 相关配置:
|
|
333
|
+
# JSON_OUTPUT_DIR = 'output' # JSON 文件输出目录
|
|
334
|
+
# DATABASE_TYPE = 'mysql' # 数据库类型: mysql/mongodb
|
|
335
|
+
# MYSQL_TABLE = '{{project_name}}_data' # MySQL 表名
|
|
336
|
+
# ======================== 使用说明 ========================
|