-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchannel_crawler.py
More file actions
368 lines (333 loc) ยท 16.2 KB
/
channel_crawler.py
File metadata and controls
368 lines (333 loc) ยท 16.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
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
import requests
from bs4 import BeautifulSoup
import time
import datetime
import json
import random
from sqlalchemy import create_engine
class TikTokChannelCrawler(object):
"""
ver 1.0, ์์ฑ์ : ๊น๋ํธ@DMK, ์์ฑ์ผ:2021.02.19, ์ต๊ทผ ์์ ์ผ:2021.02.19
์ฑ๋์ ์ด๋ฆ์ ์ธ์๋ก ๋ฐ์,
ํฑํก ๊ฐ๋ณ ์ฑ๋๊ณผ ์ฑ๋์ ๋น๋์ค๋ฅผ ํฌ๋กค๋งํ๊ณ DB์ ์ฝ์
๊น์ง ์ํํ๋ ๋ฉ์๋๋ค์ด ํฌํจ๋ ํด๋์ค์
๋๋ค.
"""
def __init__(self, user_id):
self.db_connection_info = 'postgresql://username:userpwd@localhost:5432/crawler'
self.channel_id = "" # 1232124541234 ์ ์๋ฌธ์์ดํํ
self.secret_id = "" # MAS21das123asd ํด์ฑํํ
self.user_id = user_id
self.base_url = {
'app_name': 'tiktok_web',
'device_platform': 'web',
'referer': 'https:%2F%2Fwww.google.com%2F',
'root_referer': 'https:%2F%2Fwww.google.com%2F',
'user_agent': 'Mozilla%2F5.0+(Macintosh%3B+Intel+Mac+OS+X+10_15_5)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F88.0.4324.146+Safari%2F537.36',
'cookie_enabled': 'true',
'screen_width': '1920',
'screen_height': '1080',
'browser_language':'ko-KR',
'browser_platform': 'MacIntel',
'browser_name': 'Mozilla',
'browser_version':'5.0+(Macintosh%3B+Intel+Mac+OS+X+10_15_5)+AppleWebKit%2F537.36+(KHTML,+like+Gecko)+Chrome%2F88.0.4324.146+Safari%2F537.36',
'browser_online': 'true',
'ac': '4g',
'timezone_name': 'Asia%2Fseoul',
'page_referer': 'https:%2F%2Fwww.tiktok.com%2Fsearch%3Fq%3D%25EC%25A0%259C%25EB%25A6%25AC%26lang%3Dko-KR',
'priority_region': '', # ์์
'verifyFp': 'verify_kkqg77dw_hai6t3Ps_dkIT_41yF_ApMY_G7euFo5nq2xH',
'appId': '1180',
'region': 'KR',
'appType': 't',
'isAndroid': 'false',
'isMobile': 'false',
'isIOS': 'false',
'OS': 'mac',
'did': '6925283638187689473',
'count': '30',
'cursor': '', #UNIX ์๊ฐ๊ฐ - hashtag ์ ๋ฏธ์กด์ฌ
'language': 'ko-KR',
'secUid': '' #secret_id ๋ก ์ธํ
ํ์ - hashtag์ ๋ฏธ์กด์ฌ
}
def convert_user_id_to_secret_id(self, user_id):
"""[summary]
์
๋ ฅ๋ฐ์ ์ฑ๋(ํฑํก์ปค)์ user ์์ด๋(๋ณ๊ฒฝ๊ฐ๋ฅ ๊ฐ)์ ํฌ๋กค๋ง url ์์ฑ์ ์ํ secUID๋ก ์ ํํฉ๋๋ค.
Args:
user_id (string): ์ฌ์ฉ์ ID
Returns:
secret_id(string): ์ฌ์ฉ์ secret_id(ํฑํก ์๋ฒ ๋ด๋ถ์ฉ)
"""
try:
url = f"https://www.tiktok.com/@{user_id}"
res = requests.get(url)
secuid_start_index = res.text.find('secUid')
secret_id = res.text[int(secuid_start_index):].split('"')[2]
return secret_id
except Exception as e:
print("CAN'T GET USER SECRET ID")
print(e)
return ""
def crawl_channel_info(self, secret_id):
"""[summary]
์ฑ๋ ์ ๋ณด๋ฅผ ํฌ๋กค๋ง ํ๋ ๋ฉ์๋ ๋๋ค์,์ฑ๋ID,ํ๋ก์,ํ๋ก์,์ข์์์,์ข์์ํ์,์ด๋น๋์ค์ ๋ฑ์ ํฌ๋กค๋ง
Args:
secret_id (string): ์ฌ์ฉ์ secret_id(ํฑํก ์๋ฒ ๋ด๋ถ์ฉ)
Returns:
channel_info[dict]: ์ฑ๋ ์ ๋ณด์ ๋์
๋๋ฆฌ
"""
try:
now = str(time.time()).split('.')[0]
url = 'https://t.tiktok.com/api/post/item_list/?aid=1988'
for key,value in self.base_url.items():
if key == 'cursor':
url = url + '&' + key + '=' + now + '000'
elif key == 'secUid':
url = url + '&' + key + '=' + secret_id
else:
url = url + '&' + key + '=' + value
except Exception as e:
print(e)
try:
print(url)
res = requests.get(url)
res = json.loads(str(res.text))
author_info = res['itemList'][0]['author']
author_stat = res['itemList'][0]['authorStats']
channel_info = {
'channel_id':author_info['id'],
'channel_user_id':author_info['uniqueId'],
'channel_secret_id':secret_id,
'channel_nickname':author_info['nickname'],
'channel_registered_date':datetime.date.today().isoformat(),
'channel_crawl_date':datetime.date.today().isoformat(),
'following_count':author_stat['followingCount'],
'follower_count':author_stat['followerCount'],
'heart_count':author_stat['heartCount'],
'video_count':author_stat['videoCount'],
'digg_count':author_stat['diggCount']
}
return channel_info # dict
except Exception as e:
print("CAN'T GET CHANNEL INFO")
print(e)
def crawl_video_info(self, secret_id):
"""[summary]
์ฑ๋์ด ์
๋ก๋ํ video ๋ชฉ๋ก๊ณผ ๊ฐ๋ณ video ๋ค์ ์ ๋ณด๋ฅผ ํฌ๋กค๋งํ๋ ๋ฉ์๋
๋น๋์คID,์์ฑ๋ ์ง,์ค๋ช
,ํด์ํ๊ทธ,์ข์์์,๊ณต์ ์,๋๊ธ์,์ฌ์์ ๋ฑ์ ํฌ๋กค๋ง
Args:
secret_id (string): ์ฌ์ฉ์ secret_id(ํฑํก ์๋ฒ ๋ด๋ถ์ฉ)
Returns:
video_info_list(list of dict): ๋น๋์ค ์ ๋ณด๊ฐ ๋ด๊ธด ๋์
๋๋ฆฌ์ ๋ฆฌ์คํธ
"""
video_info_list = []
#์ด๊ธฐ ์ปค์ ์ค์ (ํ์ฌ ์์ )
now = str(time.time()).split('.')[0]
cursor = now + '000'
while True:
url = 'https://t.tiktok.com/api/post/item_list/?aid=1988'
print('CURRENT CURSOR : ', cursor)
for key,value in self.base_url.items():
if key == 'cursor':
url = url + '&' + key + '=' + cursor
elif key == 'secUid':
url = url + '&' + key + '=' + secret_id
else:
url = url + '&' + key + '=' + value
try:
time.sleep(random.randrange(1, 3) +random.random())
res = requests.get(url) # randomized requesting interval
res = json.loads(str(res.text))
for item in res['itemList']:
hash_list = []
try:# if video does not have hashtag
for hashtag in item['challenges']:
hash_list.append(hashtag['title'])
except:
hash_list.append("None")
except Exception as e:
print(e)
try:
video_info = {
'video_id' : item['id'],
'channel_id' : item['author']['id'],
'video_create_date' : datetime.datetime.fromtimestamp(item['createTime']).date().isoformat(),
'video_crawl_date' : datetime.date.today().isoformat(),
'video_description' : item['desc'],
'video_hashtag': ','.join(hash_list),
'digg_count':item['stats']['diggCount'],
'share_count':item['stats']['shareCount'],
'comment_count':item['stats']['commentCount'],
'play_count':item['stats']['playCount'],
}
video_info_list.append(video_info)
print(res['hasMore'])
if res['hasMore'] == True:
cursor = res['cursor']
print('NEXT CURSOR :',cursor)
elif res['hasMore'] == False:
break
except Exception as e:
print(e)
return video_info_list
def crawl_hashtag_info(self):
"""[summary]
ํฑํก์ ์ผ๊ฐ ์ธ๊ธฐ hashtag ๋ฅผ ํฌ๋กค๋งํด์ฃผ๋ ๋ฉ์๋
ํ๊ทธ์ด๋ฆ, ์ค๋ช
, ํ๊ทธ ๋น๋์ค ์, ํ๊ทธ ์์ฒญ ์
Returns:
hashtag_info_list(list of dict): ๊ฐ๋ณ ํด์ํ๊ทธ์ ์ ๋ณด(๋์
๋๋ฆฌ)์ ๋ฆฌ์คํธ
"""
hashtag_info_list = []
url = 'https://t.tiktok.com/api/discover/challenge/?aid=1988'
for key,value in self.base_url.items():
if key == 'cursor' or key == 'secUid':#hashtag ๋ฅผ ๊ฐ์ ธ์ค๋ url์์ ํ์์๋ key,value ๋ฐฐ์
pass
else:
url = url + '&' + key + '=' + value
url = url + '&discoverType=0&needItemList=false&keyWord=&offset=0'#hashtag์ ํ์ํ ์ธ์๋ค ์ถ๊ฐ
res = requests.get(url)
res = json.loads(res.text)
for challenge in res['challengeInfoList']:
hashtag_info = {
'tag_crawl_date' : datetime.date.today().isoformat(),
'tag_id': challenge['challenge']['id'],
'tag_title': challenge['challenge']['title'],
'tag_description': challenge['challenge']['desc'],
'tag_video_count': challenge['stats']['videoCount'],
'tag_view_count': challenge['stats']['viewCount'],
}
hashtag_info_list.append(hashtag_info)
return hashtag_info_list
def upsert_db_channel_info(self, channel_info):
"""[summary]
ํฌ๋กค๋งํ ์ฑ๋ ์ ๋ณด๋ฅผ DB์ channel_list ํ
์ด๋ธ์ upsert ํด์ฃผ๋ ํจ์
Args:
channel_info (dict): ์ฑ๋์ ์ ๋ณด
"""
db_engine = create_engine(self.db_connection_info)
try:
query = '''
insert into channel_list (channel_id,channel_user_id,channel_secret_id,channel_nickname,channel_registered_date)
values ( %(channel_id)s,%(channel_user_id)s,%(channel_secret_id)s,%(channel_nickname)s,%(channel_registered_date)s)
on conflict (channel_id) DO UPDATE SET channel_user_id = %(channel_user_id)s, channel_nickname = %(channel_nickname)s;
'''
params = {
'channel_id':channel_info['channel_id'],
'channel_user_id':channel_info['channel_user_id'],
'channel_secret_id':channel_info['channel_secret_id'],
'channel_nickname':channel_info['channel_nickname'],
'channel_registered_date':channel_info['channel_registered_date']
}
db_engine.execute(query,params)## at DB channel_info table update
except Exception as e:
print(e)
try:
query = '''
insert into channel_info_daily (channel_crawl_date,channel_id,following_count,follower_count,heart_count,digg_count,video_count)
values (%(channel_crawl_date)s,%(channel_id)s,%(following_count)s,%(follower_count)s,%(heart_count)s,%(digg_count)s,%(video_count)s)
on conflict do nothing;
'''
params = {
'channel_crawl_date':channel_info['channel_crawl_date'],
'channel_id':channel_info['channel_id'],
'following_count':channel_info['following_count'],
'follower_count':channel_info['follower_count'],
'heart_count':channel_info['heart_count'],
'digg_count':channel_info['digg_count'],
'video_count':channel_info['video_count']
}
db_engine.execute(query,params)## at DB channel_info table update
except Exception as e:
print(e)
db_engine.dispose()
print("UPSERT DB CHANNEL INFO& DAILY TABLES DONE")
def upsert_db_video_info(self, video_info_list):
"""[summary]
ํฌ๋กค๋งํ ๋น๋์ค ์ ๋ณด๋ฅผ DB์ video_list ํ
์ด๋ธ ๋ฐ video_info_daily์ upsert ํด์ฃผ๋ ํจ์
Args:
video_info_list (list of dict): ๊ฐ๋ณ ๋น๋์ค์ ์ ๋ณด ๋ฆฌ์คํธ
"""
db_engine = create_engine(self.db_connection_info) # set DB engine by attribute's db info
for video_info in video_info_list:
try:# video_list tabel upsert sequence
query = '''
insert into video_list(video_id,channel_id,video_create_date,video_description,video_hashtag)
values (%(video_id)s,%(channel_id)s,%(video_create_date)s,%(video_description)s,%(video_hashtag)s)
on conflict do nothing;
'''
params = {
'video_id' : video_info['video_id'],
'channel_id' : video_info['channel_id'],
'video_create_date' : video_info['video_create_date'],
'video_description' : video_info['video_description'],
'video_hashtag': video_info['video_hashtag']
}
db_engine.execute(query,params)
except Exception as e:
print(e)
try:
query = '''
insert into video_info_daily(video_crawl_date, video_id, digg_count, share_count,comment_count,play_count)
values (%(video_crawl_date)s, %(video_id)s, %(digg_count)s, %(share_count)s,%(comment_count)s,%(play_count)s)
on conflict (video_crawl_date,video_id) do update set digg_count =%(digg_count)s, share_count = %(share_count)s, comment_count = %(comment_count)s,play_count = %(play_count)s;
'''
params = {
'video_crawl_date' : video_info['video_crawl_date'],
'video_id' : video_info['video_id'],
'digg_count':video_info['digg_count'],
'share_count':video_info['share_count'],
'comment_count':video_info['comment_count'],
'play_count':video_info['play_count'],
}
db_engine.execute(query,params)
except Exception as e:
print(e)
db_engine.dispose()
print('UPSERT DB VIDEO INFO&DAILY TABLE DONE')
def upsert_db_hashtag_info(self, hashtag_info_list):
"""[summary]
ํฌ๋กค๋งํ ํด์ํ๊ทธ ์ ๋ณด๋ฅผ DB์ hashtag_info_list ํ
์ด๋ธ์ upsert ํด์ฃผ๋ ํจ์
Args:
hashtag_info_list (list of dict): ๊ฐ๋ณ ํด์ํ๊ทธ ์ ๋ณด์ ๋ฆฌ์คํธ
"""
db_engine = create_engine(self.db_connection_info) # set DB engine by attribute's db info
for hashtag in hashtag_info_list:
try:
query = '''
insert into hashtag_info_daily(tag_crawl_date, tag_id, tag_title, tag_description,tag_video_count,tag_view_count)
values (%(tag_crawl_date)s, %(tag_id)s, %(tag_title)s, %(tag_description)s,%(tag_video_count)s,%(tag_view_count)s)
on conflict (tag_crawl_date,tag_id) do nothing;
'''
params = {
'tag_crawl_date' : hashtag['tag_crawl_date'],
'tag_id': hashtag['tag_id'],
'tag_title': hashtag['tag_title'],
'tag_description': hashtag['tag_description'],
'tag_video_count': hashtag['tag_video_count'],
'tag_view_count': hashtag['tag_view_count'],
}
db_engine.execute(query,params)
except Exception as e:
print(e)
db_engine.dispose()
print("UPSERT DB HASHTAG DONE.")
def start(self):
secret_id = self.convert_user_id_to_secret_id(self.user_id)
self.secret_id = secret_id
print("CHANNEL SECRET ID : ", secret_id)
try: # channel & video crawling
channel_info = self.crawl_channel_info(self.secret_id)
video_info_list = self.crawl_video_info(self.secret_id)
self.upsert_db_channel_info(channel_info)
self.upsert_db_video_info(video_info_list)
except Exception as e:
print(e)
try: # tag crawling
hashtag_info_list = self.crawl_hashtag_info()
self.upsert_db_hashtag_info(hashtag_info_list)
except Exception as e:
print(e)
if __name__ == "__main__":
print("INPUT TIKTOK CHANNEL ID : ")
user_id = input()
crawler = TikTokChannelCrawler(user_id)
crawler.start()
print("ALL DONE")