forked from jarieshan/Zhihu-Spider
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
284 lines (254 loc) · 10.6 KB
/
main.py
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# -*- coding: utf-8 -*-
"""
@Author : 满目皆星河
@Project : 知乎
@File : main.py
@Time : 2020/11/13 0:53
@Description :
"""
import redis
import config
from time import sleep
from threading import Thread
from frame import SpiderFrame
from frame.mail import send_mail
logger = SpiderFrame.logger
redis = redis.Redis(host=config.REDIS_HOST, port=config.REDIS_PORT, password=config.REDIS_PASSWORD)
class TopicSpider(Thread):
def __init__(self):
logger.info("TopicSpider init...")
super().__init__()
# url_manager方法已经内置,只需要使用id_manager传入ID参数即可
self.id_manager = SpiderFrame.UrlManager(db_set_name=config.TOPIC_ID_SET, use_redis=config.USE_REDIS)
self.exit_code = 1
def run(self):
from utils import topic
logger.info("TopicSpider thread start...")
_id = ""
try:
while self.id_manager.list_not_null():
logger.warning("Len {0}: {1}".format(config.TOPIC_ID_SET, redis.llen("list_"+config.TOPIC_ID_SET)))
_id = self.id_manager.get()
try:
topic.spider(_id)
except:
continue
sleep(15)
self.exit_code = 0
except Exception as e:
# 之前的报错信息已被记录
logger.critical("Unexpected Exit TopicSpider: {0}, Message: {1}".format(_id, e), exc_info=True)
# send_mail("TopicSpider发生意料之外的错误,已退出线程")
finally:
logger.warning("TopicSpider finished")
if self.exit_code == 0:
topic.html_downloader.proxies.__exit__()
class QuestionSpider(Thread):
def __init__(self):
logger.info("QuestionSpider init...")
super().__init__()
self.exit_code = 1
self.flag = True
# url_manager方法已经内置,只需要使用id_manager传入ID参数即可
self.id_manager = SpiderFrame.UrlManager(db_set_name=config.QUESTION_ID_SET, use_redis=config.USE_REDIS)
def __exit__(self):
logger.warning("强制终止线程: QuestionSpider")
self.flag = False
def run(self):
from utils import question
logger.info("QuestionSpider thread start...")
_id = ''
try:
while self.flag:
if self.id_manager.list_not_null():
_id = self.id_manager.get()
try:
question.spider(_id)
except:
continue
else:
sleep(5)
self.exit_code = 0
except Exception as e:
# 之前的报错信息已被记录
logger.critical("Unexpected Exit QuestionSpider: {0}, Message: {1}".format(_id, e), exc_info=True)
# send_mail("QuestionSpider发生意料之外的错误,已退出线程")
finally:
logger.warning("QuestionSpider exited")
if self.exit_code == 0:
question.html_downloader.proxies.__exit__()
class CommentSpider(Thread):
def __init__(self):
logger.info("CommentSpider init...")
super().__init__()
self.exit_code = 1
self.flag = True
# url_manager方法已经内置,只需要使用id_manager传入ID参数即可
self.id_manager = SpiderFrame.UrlManager(db_set_name=config.ANSWER_ID_SET, use_redis=config.USE_REDIS)
def __exit__(self):
logger.warning("强制终止线程: CommentSpider")
self.flag = False
def run(self):
from utils import comment
_id = ''
try:
logger.info("CommentSpider thread start...")
while self.flag:
if self.id_manager.list_not_null():
_id = self.id_manager.get()
try:
comment.spider(_id)
except:
continue
else:
sleep(5)
self.exit_code = 0
except Exception as e:
# 之前的报错信息已被记录
logger.critical("Unexpected Exit CommentSpider: {0}, Message: {1}".format(_id, e), exc_info=True)
# send_mail("CommentSpider发生意料之外的错误,已退出线程")
finally:
logger.warning("CommentSpider finished")
if self.exit_code == 0:
comment.html_downloader.proxies.__exit__()
class UserSpider(Thread):
def __init__(self):
logger.info("UserSpider init...")
super().__init__()
self.exit_code = 1
self.flag = True
# url_manager方法已经内置,只需要使用id_manager传入ID参数即可
self.id_manager = SpiderFrame.UrlManager(db_set_name=config.USER_ID_SET, use_redis=config.USE_REDIS)
def __exit__(self):
logger.warning("强制终止线程: UserSpider")
self.flag = False
def run(self):
from utils import user
logger.info("UserSpider thread start...")
_id = ''
try:
while self.flag:
if self.id_manager.list_not_null():
_id = self.id_manager.get()
try:
user.spider(_id)
except:
continue
else:
sleep(5)
self.exit_code = 0
except Exception as e:
# 之前的报错信息已被记录
logger.critical("Unexpected Exit UserSpider: {0}, Message: {1}".format(_id, e), exc_info=True)
# send_mail("UserSpider发生意料之外的错误,已退出线程")
finally:
logger.warning("UserSpider finished")
if self.exit_code == 0:
user.html_downloader.proxies.__exit__()
def RecoverErrorID():
keys = redis.keys("*")
for key in keys:
try:
int(key)
url = redis.get(key).decode("utf-8").split("/")
if url[5] == "answers":
redis.rpush("list_"+config.ANSWER_ID_SET, url[6])
# redis.delete(key)
elif url[5] == "questions":
redis.rpush("list_"+config.QUESTION_ID_SET, url[6])
# redis.delete(key)
elif url[5] == "topics":
redis.rpush("list_"+config.TOPIC_ID_SET, url[6])
# redis.delete(key)
except:
pass
class running(Thread):
def __init__(self):
super(running, self).__init__()
def run(self):
TS = TopicSpider()
QS = QuestionSpider()
CS = CommentSpider()
US = UserSpider()
logger.info("Processing Error Data")
RecoverErrorID()
TS.start()
logger.info("Next thread will be start after 7.5s")
sleep(7.5)
QS.start()
logger.info("Next thread will be start after 7.5s")
sleep(7.5)
CS.start()
logger.info("Next thread will be start after 7.5s")
sleep(7.5)
US.start()
logger.warning("爬虫进程启动完成,启动监控进程")
# watching
TS_i = QS_i = CS_i = US_i = 1
while True:
if (TS.exit_code != 0 or TS.id_manager.list_not_null()) and not TS.is_alive():
for i in range(1, 4):
if TS.is_alive():
continue
logger.warning("TS is exit, try active it. ({0}/3)".format(TS_i))
TS = TopicSpider()
TS.start()
sleep(5)
if i == 3 and not TS.is_alive():
logger.error("Active thread TS failed")
send_mail("TS is exit and try to activate it failed")
if (QS.exit_code != 0 or TS.id_manager.list_not_null()) and not QS.is_alive():
for i in range(1, 4):
if QS.is_alive():
QS_i = 1
continue
logger.warning("QS is exit, try active it. ({0}/3)".format(QS_i))
QS = QuestionSpider()
QS.start()
sleep(5)
if i == 3 and not QS.is_alive():
logger.error("----- Active thread QS failed -----")
send_mail("QS is exit and try to activate it failed")
if (CS.exit_code != 0 or TS.id_manager.list_not_null()) and not CS.is_alive():
for i in range(1, 4):
if CS.is_alive():
CS_i = 1
continue
logger.warning("QS is exit, try active it. ({0}/3)".format(CS_i))
CS = CommentSpider()
CS.start()
sleep(5)
if i == 3 and not CS.is_alive():
logger.error("----- Active thread CS failed -----")
send_mail("CS is exit and try to activate it failed")
if (US.exit_code != 0 or TS.id_manager.list_not_null()) and not US.is_alive():
for i in range(1, 4):
if US.is_alive():
US_i = 1
continue
logger.warning("US is exit, try active it. ({0}/3)".format(US_i))
US = UserSpider()
US.start()
sleep(5)
if i == 3 and not US.is_alive():
logger.error("----- Active thread US failed -----")
send_mail("US is exit and try to activate it failed")
if TS.exit_code == 0 and QS.exit_code == 0 and CS.exit_code == 0 and US.exit_code == 0:
logger.critical("----- All thread exited and can't be actived, main thread is exiting -----")
return
if (TS.is_alive() or TS.exit_code == 0) and (QS.is_alive() or QS.exit_code == 0) and (CS.is_alive() or CS.exit_code == 0) and (US.is_alive() or US.exit_code == 0):
logger.info("----- ALL THREAD IS ALIVE -----")
if TS.exit_code == 0 and not QS.id_manager.list_not_null():
if QS.flag:
QS.__exit__()
if QS.exit_code == 0 and not CS.id_manager.list_not_null():
if CS.flag:
CS.__exit__()
if CS.exit_code == 0 and not US.id_manager.list_not_null():
if US.flag:
US.__exit__()
sleep(10)
if __name__ == '__main__':
redis.delete("ProxiesThreadCode_{0}".format(config.THREAD_ID))
r1 = running()
r1.start()