spider_control.py
6.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from flask import Blueprint, jsonify, request, render_template
import json
import os
from datetime import datetime
import threading
from queue import Queue
import asyncio
import websockets
import logging
from spider.spiderData import SpiderData
# 创建蓝图
spider_bp = Blueprint('spider', __name__)
# 创建日志记录器
logger = logging.getLogger('spider_control')
logger.setLevel(logging.INFO)
# 存储WebSocket连接的集合
websocket_connections = set()
# 创建消息队列
message_queue = Queue()
# 默认配置
DEFAULT_CONFIG = {
'crawlDepth': 3,
'interval': 5,
'maxRetries': 3,
'timeout': 30
}
def load_config():
"""加载爬虫配置"""
config_path = os.path.join(os.path.dirname(__file__), '../spider/config.json')
try:
if os.path.exists(config_path):
with open(config_path, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"加载配置文件失败: {e}")
return DEFAULT_CONFIG
def save_config(config):
"""保存爬虫配置"""
config_path = os.path.join(os.path.dirname(__file__), '../spider/config.json')
try:
with open(config_path, 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=4)
return True
except Exception as e:
logger.error(f"保存配置文件失败: {e}")
return False
async def broadcast_message(message):
"""广播消息到所有WebSocket连接"""
if not websocket_connections:
return
for websocket in websocket_connections.copy():
try:
await websocket.send(json.dumps(message))
except websockets.exceptions.ConnectionClosed:
websocket_connections.remove(websocket)
except Exception as e:
logger.error(f"发送WebSocket消息失败: {e}")
websocket_connections.remove(websocket)
def spider_worker(topics, parameters):
"""爬虫工作线程"""
total_topics = len(topics)
completed_topics = 0
try:
spider = SpiderData()
for topic in topics:
try:
# 更新进度
progress = int((completed_topics / total_topics) * 100)
asyncio.run(broadcast_message({
'type': 'progress',
'value': progress
}))
# 发送开始爬取的日志
asyncio.run(broadcast_message({
'type': 'log',
'message': f'开始爬取话题: {topic}'
}))
# 执行爬取
spider.crawl_topic(
topic=topic,
depth=parameters['crawlDepth'],
interval=parameters['interval'],
max_retries=parameters['maxRetries'],
timeout=parameters['timeout']
)
completed_topics += 1
# 发送完成爬取的日志
asyncio.run(broadcast_message({
'type': 'log',
'message': f'话题 {topic} 爬取完成'
}))
except Exception as e:
# 发送错误日志
asyncio.run(broadcast_message({
'type': 'log',
'message': f'爬取话题 {topic} 时出错: {str(e)}'
}))
# 更新最终进度
asyncio.run(broadcast_message({
'type': 'progress',
'value': 100
}))
# 发送完成消息
asyncio.run(broadcast_message({
'type': 'log',
'message': '所有话题爬取完成'
}))
except Exception as e:
# 发送错误日志
asyncio.run(broadcast_message({
'type': 'log',
'message': f'爬虫任务执行出错: {str(e)}'
}))
@spider_bp.route('/spider/control')
def spider_control():
"""渲染爬虫控制页面"""
return render_template('spider_control.html')
@spider_bp.route('/api/spider/start', methods=['POST'])
def start_spider():
"""启动爬虫任务"""
try:
data = request.get_json()
topics = data.get('topics', [])
parameters = data.get('parameters', DEFAULT_CONFIG)
if not topics:
return jsonify({
'success': False,
'message': '请选择至少一个话题'
})
# 启动爬虫线程
thread = threading.Thread(
target=spider_worker,
args=(topics, parameters),
daemon=True
)
thread.start()
return jsonify({
'success': True,
'message': '爬虫任务已启动'
})
except Exception as e:
logger.error(f"启动爬虫任务失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@spider_bp.route('/api/spider/save-config', methods=['POST'])
def save_spider_config():
"""保存爬虫配置"""
try:
config = request.get_json()
if save_config(config):
return jsonify({
'success': True,
'message': '配置保存成功'
})
else:
return jsonify({
'success': False,
'message': '配置保存失败'
})
except Exception as e:
logger.error(f"保存配置失败: {e}")
return jsonify({
'success': False,
'message': str(e)
})
@spider_bp.websocket('/ws/spider-status')
async def spider_status_socket():
"""WebSocket连接处理"""
try:
websocket = websockets.WebSocketServerProtocol()
websocket_connections.add(websocket)
try:
while True:
# 保持连接活跃
await websocket.ping()
await asyncio.sleep(30)
except websockets.exceptions.ConnectionClosed:
pass
finally:
websocket_connections.remove(websocket)
except Exception as e:
logger.error(f"WebSocket连接处理失败: {e}")