-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkingThread.py
399 lines (316 loc) · 15.6 KB
/
workingThread.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
"""
爬取策略
根据一个用户作为seed,将该用户的所有followed加入到seed集合
然后从这些seed集合中选取最近听歌超过20首的用户进行爬取,爬取这个用户的信息和最近听歌的信息
直到歌曲总数达到10w首位置
其中爬取用户的线程和爬取单个歌曲的线程都是单元素的线程
也就是说一个线程专门用来负责爬取一个用户或者一首歌
然后全局的线程总数保证为K个固定值
数据库在读写的时候,每个爬取线程都会向内存中写入信息
然后内存主线程在积累到了一定的数量的歌曲和用户之后写入到数据库线程中
"""
from queue import Queue
from UserSpider import UserSpider
from SongSpider import SongSpider
from database_demo import db_cls
import threading
import time
import random
import proxy
import os
visited_user_list = [1]
visited_song_list = []
class ThreadSafeData:
def __init__(self):
self.allSongids = []
self.songSeedsList = Queue()
self.userSeedsList = Queue()
self.gsong_SongInfoList = []
self.gsong_Song2SingerList = []
self.guser_UserInfosList = []
self.guser_User2SongList = []
self.guser_User2SonglistList = []
self.guser_FollowList = []
self.lock_allSongids = threading.Lock()
self.lock_gsong_SongInfoList = threading.Lock()
self.lock_gsong_Song2SingerList = threading.Lock()
self.lock_guser_UserInfosList = threading.Lock()
self.lock_guser_User2SongList = threading.Lock()
self.lock_guser_User2SonglistList = threading.Lock()
self.lock_guser_FollowList = threading.Lock()
self.how_many_threads_after_previous_db_write = 0
self.lock_how_many_threads_after_previous_db_write = threading.Lock()
self.db = None
def create_db(self, db_filename = "pj_data.db"):
self.db = db_cls(db_filename = db_filename)
global visited_song_list
global visited_user_list
vsongs = self.db.read_Data("Select * from Song")
for eachSong in vsongs:
id = list(eachSong)[0]
if id not in visited_song_list:
visited_song_list.append(id)
vusers = self.db.read_Data("Select * from User_Table")
for eachUser in vusers:
id = list(eachUser)[0]
if id not in visited_user_list:
visited_user_list.append(list(eachUser)[0])
def addNewSongs_threadSafe(self, song_info_list, song2singer_list):
self.lock_gsong_SongInfoList.acquire()
self.gsong_SongInfoList.append(song_info_list)
self.lock_gsong_SongInfoList.release()
self.lock_gsong_Song2SingerList.acquire()
self.gsong_Song2SingerList.extend(song2singer_list)
self.lock_gsong_Song2SingerList.release()
#this method will also extend the global seed list
def addNewUsers_threadSafe(self, user_infos_list, user2song_list, user2songlist_list, follow_list):
self.lock_guser_UserInfosList.acquire()
self.guser_UserInfosList.append(user_infos_list)
self.lock_guser_UserInfosList.release()
self.lock_guser_User2SongList.acquire()
self.guser_User2SongList.extend(user2song_list)
for eachSong in user2song_list:
self.songSeedsList.put(list(eachSong)[1])
self.lock_guser_User2SongList.release()
self.lock_guser_User2SonglistList.acquire()
self.guser_User2SonglistList.extend(user2songlist_list)
self.lock_guser_User2SonglistList.release()
self.lock_guser_FollowList.acquire()
self.guser_FollowList.extend(follow_list)
for eachFollow in follow_list:
self.userSeedsList.put(list(eachFollow)[1])
self.lock_guser_FollowList.release()
def writeIntoDatabase_threadSafe(self):
self.lock_gsong_SongInfoList.acquire()
self.lock_gsong_Song2SingerList.acquire()
debug_print_thread(('song info list', self.gsong_SongInfoList))
debug_print_thread(('song2singer list', self.gsong_Song2SingerList))
self.db.write_Song_infos(self.gsong_SongInfoList, self.gsong_Song2SingerList)
# self.db.create_index()
self.gsong_SongInfoList.clear()
self.gsong_Song2SingerList.clear()
self.lock_gsong_Song2SingerList.release()
self.lock_gsong_SongInfoList.release()
self.lock_guser_UserInfosList.acquire()
self.lock_guser_FollowList.acquire()
self.lock_guser_User2SongList.acquire()
self.lock_guser_User2SonglistList.acquire()
debug_print_thread(('user info db', self.guser_UserInfosList))
debug_print_thread(('user recent songs db', self.guser_User2SongList))
debug_print_thread(('user songlist db', self.guser_User2SonglistList))
debug_print_thread(('user follow db', self.guser_FollowList))
self.db.write_User_infos(
user_infos_list=self.guser_UserInfosList,
user2song_list=self.guser_User2SongList,
user2songlist_list=self.guser_User2SonglistList,
follow_list=self.guser_FollowList
)
# self.db.create_index()
self.guser_UserInfosList.clear()
self.guser_User2SongList.clear()
self.guser_User2SonglistList.clear()
self.guser_FollowList.clear()
self.lock_guser_User2SonglistList.release()
self.lock_guser_User2SongList.release()
self.lock_guser_FollowList.release()
self.lock_guser_UserInfosList.release()
def set_threads_after_db(self, num, increase=False):
self.lock_how_many_threads_after_previous_db_write.acquire()
if increase: self.how_many_threads_after_previous_db_write += 1
else: self.how_many_threads_after_previous_db_write = num
self.lock_how_many_threads_after_previous_db_write.release()
def debug_print_thread(msg, exe=True):
if exe: print('[*', threading.get_ident(), '*]', msg)
class ThreadPool:
def __init__(self, threadMaxNums = 1):
self.THREAD_MAX = threadMaxNums
self.currentAvailThreads = self.THREAD_MAX
self.availThreadCondi = threading.Condition()
self.databaseWriteInCondi = threading.Condition()
self.lock_availableThreads = threading.Lock()
self.dataSpace = ThreadSafeData()
#initialize the user seed list
self.dataSpace.userSeedsList.put(340056317)
self.dataSpace.userSeedsList.put(350714427)
self.dataSpace.userSeedsList.put(20888663)
self.dataSpace.userSeedsList.put(588707084)
db_temp = db_cls("pj_data.db")
user_tables = db_temp.read_Data("Select * from Follow")
for i in range(3):
self.dataSpace.userSeedsList.put(list(random.choice(user_tables))[1])
db_temp.close_db()
candidate_songs_file = open("./candidate_songs.txt")
lines = candidate_songs_file.readlines()
for line in lines:
seed = int(line.strip())
# debug_print_thread(seed, True)
self.dataSpace.songSeedsList.put(seed)
self.__first_db_initialize_flag = False
def _util_scrapySingleUser(userUrl, proxyUrl):
up = UserSpider(userUrl, proxyUrl)
# up.getAllContents()
res = up.getAllContents()
if not up.UserConditionSatisfy20Songs():
debug_print_thread('not satisfying with len ' +str(len(up.get_user2song_list())) )
#pass do nothing
elif res == "ok":
#save it to class global variables
debug_print_thread('satisfying the requirements, returning')
debug_print_thread(('[**] song id seed list', up.get_user2song_list()))
return [up.get_user_info(), up.get_user2song_list(), up.get_user2songlist_list(), up.get_follow_list()]
else:
return None
def _thread_scrapyUserAndSave(self, userUrl, threadSafeData, proxyUrl):
debug_print_thread("new [*user*] thread seed={0} proxy={1}".format(userUrl, proxyUrl), True)
res = ThreadPool._util_scrapySingleUser(userUrl, proxyUrl)
if(res != None):
[user_infos_list, user2song_list, user2songlist_list, follow_list] = res
debug_print_thread('adding new to data')
debug_print_thread(user_infos_list)
debug_print_thread(user2song_list)
debug_print_thread(user2songlist_list)
debug_print_thread(follow_list)
threadSafeData.addNewUsers_threadSafe(
tuple(user_infos_list),
list(user2song_list),
list(user2songlist_list),
list(follow_list)
)
debug_print_thread('ending this user thread')
self.lock_availableThreads.acquire()
self.currentAvailThreads += 1
self.lock_availableThreads.release()
def _util_scrapySong(songUrl, proxyUrl):
try:
sp = SongSpider(songUrl, proxyUrl)
debug_print_thread("break point here")
source = sp.getPageSource()
debug_print_thread("successfully get the page")
res = sp.getInfo(source)
except Exception:
print(Exception.message)
debug_print_thread("exception occurred in this song thread")
return None
if res == "ok":
debug_print_thread("successful scapy song, add in set")
song_info = sp.getSongRequiredTuple()
song_artists = sp.getSongArtistsList()
return [song_info, song_artists]
else:
debug_print_thread("song info not valid, returning None")
return None
def _thread_scrapySongAndSave(self, songUrl, threadSafeData, proxyUrl):
debug_print_thread("new [*song*] thread seed={0} proxy={1}".format(songUrl, proxyUrl), True)
res = ThreadPool._util_scrapySong(songUrl, proxyUrl)
if(res != None):
[song_info_tuple, song_artists_list] = res
threadSafeData.addNewSongs_threadSafe(
tuple(song_info_tuple),
list(song_artists_list)
)
debug_print_thread("successfully scraped a new song")
debug_print_thread('ending this song thread')
self.lock_availableThreads.acquire()
self.currentAvailThreads += 1
self.lock_availableThreads.release()
def newThread_User(self, userUrl, proxyUrl):
thread = threading.Thread(
target=ThreadPool._thread_scrapyUserAndSave,
args=(self, userUrl, self.dataSpace, proxyUrl)
)
return thread
def newThread_Song(self, songUrl, proxyUrl):
thread = threading.Thread(
target=ThreadPool._thread_scrapySongAndSave,
args=(self, songUrl, self.dataSpace, proxyUrl),
)
return thread
def mainThread(self):
while True:
# debug_print_thread(self.dataSpace.gsong_SongInfoList, True)
self.lock_availableThreads.acquire()
for i in range(self.currentAvailThreads):
# proxyUrl = proxy.getProxy()
proxyUrl = 'fuckingWYY'
if self.dataSpace.userSeedsList.empty():
debug_print_thread('current seed list empty', True)
break
else:
debug_print_thread('start a new thread')
#randomly decide next is user or song
randres = random.choice([1,2])
if self.dataSpace.userSeedsList.empty(): randres = 2
elif self.dataSpace.songSeedsList.empty(): randres = 1
randres = 2
if(randres == 1): #then next user
id_next = self.dataSpace.userSeedsList.get()
while id_next in visited_user_list:
id_next = self.dataSpace.userSeedsList.get()
user_thread = self.newThread_User('https://music.163.com/#/user/home?id=' + str(id_next), proxyUrl)
user_thread.start()
visited_user_list.append(id_next)
self.currentAvailThreads -= 1
self.dataSpace.set_threads_after_db(0, increase=True)
elif (randres == 2): #then next song
id_next = self.dataSpace.songSeedsList.get()
while id_next in visited_song_list:
id_next = self.dataSpace.songSeedsList.get()
song_thread = self.newThread_Song('https://music.163.com/#/song?id=' + str(id_next), proxyUrl)
song_thread.start()
visited_song_list.append(id_next)
self.currentAvailThreads -= 1
self.dataSpace.set_threads_after_db(0, increase=True)
self.lock_availableThreads.release()
if self.availThreadCondi.acquire():
self.availThreadCondi.notify()
self.availThreadCondi.wait()
self.availThreadCondi.release()
def listenerThread(self):
while True:
#trying to produce new threads
if(self.availThreadCondi.acquire()):
if(self.currentAvailThreads > 0 and not self.dataSpace.songSeedsList.empty()):
self.availThreadCondi.notify()
self.availThreadCondi.wait()
self.availThreadCondi.release()
if(self.databaseWriteInCondi.acquire()):
if(len(self.dataSpace.guser_UserInfosList) > 5 or len(self.dataSpace.gsong_SongInfoList) > 5):
self.databaseWriteInCondi.notify()
self.databaseWriteInCondi.wait()
self.databaseWriteInCondi.release()
if self.dataSpace.how_many_threads_after_previous_db_write >= 50:
os._exit(1)
def databaseWriteInThread(self):
while True:
if(self.databaseWriteInCondi.acquire()):
if(len(self.dataSpace.guser_UserInfosList) >= 3 or len(self.dataSpace.gsong_SongInfoList) >= 3):
# if(not self.__first_db_initialize_flag):
self.dataSpace.create_db()
# self.__first_db_initialize_flag = False
self.dataSpace.writeIntoDatabase_threadSafe()
#then display the current stage information
db = self.dataSpace.db
songs = db.read_Data(sql_query="Select * FROM Song")
debug_print_thread("Main Thread, display all available songs, totally " + str(len(songs)), True)
for song in songs:
debug_print_thread(song)
users = db.read_Data(sql_query='Select * FROM User_Table')
debug_print_thread("Main Thread, display all available users, totally " + str(len(users)), True)
for user in users:
debug_print_thread(user)
db.close_db()
self.dataSpace.set_threads_after_db(0)
self.databaseWriteInCondi.notify()
self.databaseWriteInCondi.wait()
self.databaseWriteInCondi.release()
if __name__ == "__main__":
try:
tp = ThreadPool(threadMaxNums=12)
threadingMain = threading.Thread(target=tp.mainThread, args=())
threadingListener = threading.Thread(target=tp.listenerThread, args=())
threadDb = threading.Thread(target=tp.databaseWriteInThread, args=())
threadingMain.start()
threadingListener.start()
threadDb.start()
finally:
pass