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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# -*- coding: utf-8 -*-
"""Untitled28.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/
"""

!pip install beautifulsoup4

# coding: UTF-8
import urllib.request
import urllib.parse
import re
import time
import json
from bs4 import BeautifulSoup
import collections

words = "ocaml"
keywords = urllib.parse.quote(words)
target_url = "https://www.youtube.com/results?search_query=" + keywords
html = urllib.request.urlopen(target_url).read()
html_strings = html.decode()
del(html)

soup = BeautifulSoup(html_strings, 'html.parser')
for ind,script_tag in enumerate(soup.find_all('script')):
    if (ma := re.search(r"var\sytInitialData", str(script_tag))):
    #if ind == 33:
        json_strings = str(script_tag)[ma.end()+3:-10]
        #json_strings = str(script_tag)[58:-10]
del(soup)

j_dict = json.loads(json_strings)

#print(json.dumps(j_dict, indent=1))
li_contents = []

#for k1,v1 in j_dict['contents'].items():
#    if (k1 == 'twoColumnSearchResultsRenderer'):
#        for k2,v2 in v1.items():
#            if (k2 == 'primaryContents'):
#                for k3,v3 in v2.items():
#                    if (k3 == 'sectionListRenderer'):
#                        for k4,v4 in v3.items():
#                            if (k4 == 'contents'):
#                                for ind,v5 in enumerate(v4):
#                                    if (ind == 0):
#                                        for k6,v6 in v5.items():
#                                            if (k6 == 'itemSectionRenderer'):
#                                                for k7,v7 in v6.items():
#                                                    if (k7 == 'contents'):
#                                                        li_contents.extend(v7)

v7 = j_dict['contents']['twoColumnSearchResultsRenderer']['primaryContents']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents']

li_contents.extend(v7)
del j_dict

#print(len(li_contents))

uniq_videoid = [] 
uniq_title = [] 

def recur(v):
    if type(v) == list:
#        print('list',v)
#        print()
        for lv in v:
            recur(lv)
    elif type(v) == dict:
#        print('dict',v)
        for dk,dv in v.items():
            recur2(dk,dv)
#    print()

def recur2(k,v):
    #print('{' + k + ' : ' + str(v)+ '}')
    #print()
    if(k=='videoId' or k=='title'):
        if k== 'videoId':
#            print(v)
            if not(v in uniq_videoid):
                    uniq_videoid.append(v)
        if k== 'title':
            if (check := 'runs' in v):
#               print(v['runs'][0]['text'])
                if not(v['runs'][0]['text'] in uniq_title):
                    uniq_title.append(v['runs'][0]['text'])

#    print()
    if type(v) == list:
        for ind,lv in enumerate(v):
#            print('list',ind,'=>')
            recur(lv)
    elif type(v) == dict:
#        print('dict',v)
#        print()
        for dk,dv in v.items():
            recur2(dk,dv)

while len(li_contents) > 0 :
    head = li_contents.pop(0)
    recur(head)

zip_list = zip(uniq_videoid,uniq_title)

#for ind,x in enumerate(zip_list):
#    print (ind,x)
#    print ()

# check values 
search_list_temporary = [x for x in zip_list if x != '' ]
del(zip_list)
uniq_videoid.clear() 
uniq_title.clear()
######## ##### ###### ###### ###### ###### ###### ###### 
#
#for ind,p in enumerate(search_list_temporary):
#    print(ind, p)
#print()
#
######## ##### ###### ###### ###### ###### ###### ###### 

# check keywords in video title 
search_list = [ x for x in search_list_temporary if re.search(rf'(?i){words}',x[1]) ]
del(search_list_temporary)

#for ind,p in enumerate(search_list):
#    print(ind, p)
#print()
#
######## ##### ###### ###### ###### ###### ###### ###### 

video_list_0 = []
already_list = []
total_list = []
id_cell_1 = {}
id_cell_2 = {}

#video_list_0.extend(search_list) # [0] videoid / [1] title
search_list2 = [x[0] for x in search_list] # [0] videoid / [1] title
video_list_0.extend(search_list2) # [0] videoid

def first_gether(words, target_url, total_list, id_cell_1, id_cell_2):

    id_cell_seconds = {}
    id_cell_title = {}

    ommit = target_url.replace("https://www.youtube.com/watch?v=",'') # videoid

    html = urllib.request.urlopen(target_url).read()
    html_strings = html.decode()
    del(html)
    soup = BeautifulSoup(html_strings, 'html.parser')
    for ind,script_tag in enumerate(soup.find_all('script')):
        if (ma1 := re.search(r"var\sytInitialData",str(script_tag))):
        #if ind == 43:
            json_strings = str(script_tag)[ma1.end()+3:-10]
            #json_strings = str(script_tag)[58:-10]

    #page_title = soup.find('title')
    #print(page_title)
    del(soup)
    print()

    j_dict = json.loads(json_strings)
    current_item_data = j_dict['contents']['twoColumnWatchNextResults']['results']
    secondary_data = j_dict['contents']['twoColumnWatchNextResults']['secondaryResults']

    del j_dict
    current_title = [] ## only one size list
    current_videoid = [] ## only one size list
    current_description = [] ## only one size list

    def f1(v):###:###:###:###:###:###
        if type(v) == list:
    #        print('list',v)
    #        print()
            for lv in v:
                f1(lv)
        elif type(v) == dict:
    #        print('dict',v)
            for dk,dv in v.items():
                f2(dk,dv)
    #    print()

    def f2(k,v):
    #    print('{' + k + ' : ' + str(v)+ '}')
    #    print()
        if(k=='dateText'):
#            print(k,v['simpleText'])
            pass
        if(k=='description'):
#            print(v['runs'][0]['text'])
            current_description.append(v['runs'][0]['text'])
        if(k=='videoId' or k=='title'):

            if k== 'videoId':
#               print(v)
                if (empty := (len(current_videoid) < 1)):
                    if not(v in current_videoid):
                        current_videoid.append(v)
            if k== 'title':
                if (empty := (len(current_title) < 1)):
                    if (check := 'runs' in v):
                        if not(v['runs'][0]['text'] in current_title):
#                           print(v['runs'][0]['text'])
                            current_title.append(v['runs'][0]['text'])
    #    print()

        if type(v) == list:
            for ind,lv in enumerate(v):
    #            print('list',ind,'=>')
                f1(lv)
        elif type(v) == dict:
    #        print('dict',v)
    #        print()
            for dk,dv in v.items():
                f2(dk,dv)
    ###:###:###:###:###:###

    f1(current_item_data) # recursive function

#    print()
#    print('current contents')
#    print(current_videoid)
#    print(current_title)
#    print()

    uniq_videoids = []
    uniq_titles = []

    def rr(v):
        if type(v) == list:
    #        print('list',v)
    #        print()
            for lv in v:
                rr(lv)
        elif type(v) == dict:
    #        print('dict',v)
            for dk,dv in v.items():
                rr2(dk,dv)
    #    print()

    def rr2(k,v):
#        print('{' + k + ' : ' + str(v)+ '}')
#        print()
        if(k=='videoId' or k=='title'):
            if k== 'videoId':
#                   print(v)
                if str(v) != ommit:
                    uniq_videoids.append(v)
                else:
#                   print(v)
                    pass
            if k== 'title':
                if (check := 'accessibility' in v): # key check
                    if v['accessibility']['accessibilityData']['label'] != None:
                        if not(v['accessibility']['accessibilityData']['label'] in uniq_titles):
                            uniq_titles.append(v['accessibility']['accessibilityData']['label'])

    #    print()
        if type(v) == list:
            for ind,lv in enumerate(v):
    #            print('list',ind,'=>')
                rr(lv)
        elif type(v) == dict:
    #        print('dict',v)
    #        print()
            for dk,dv in v.items():
                rr2(dk,dv)

    rr(secondary_data)

    poplist = []
    for i,x in enumerate(uniq_videoids):
        k = uniq_videoids.count(x)
        if k > 3:
            pass
        else:
            poplist.append(i)

    for x in poplist:
        uniq_videoids.pop(x)
    poplist.clear()

    new_uniq_videoids = []

    for x in uniq_videoids:
        if (check := x in new_uniq_videoids):
            pass
        else:
            new_uniq_videoids.append(x)
# check 
#    print('--')
#    print(len(new_uniq_videoids))
#    print(len(uniq_titles))
#    print('--')

    titles_videoids = zip(uniq_titles,new_uniq_videoids)
    # check
    #    for z in titles_videoids:
    #        print('----------------------')
    #        print(*z)
    #    print('----------------------')

    videoid_list = []
    title_list = []
    durations_list = []
    channelid_list = []
    titles_videoids2 = [ x for x in titles_videoids if re.search(rf'(?i){words}',x[0])]
    video_list = []
    id_data = [x[1] for x in titles_videoids2]
    video_list.extend(id_data)

    title = re.search(r"(?<=\<title\>).*?(?=\<\/title\>)",html_strings)
    if title is None:
        print("skip")
    else:
        title_strings = title.group()

        kakawari = re.search(rf'(?i){words}',title_strings)
        kakawari2 = re.search(rf'(?i){words}',str(current_description[0]))

        if (kakawari is None) and (kakawari2 is None):
            print()
            print(title_strings)
            print("skip (not relevant)")
            print()
            pass
        else:         
            total_list.append(target_url)
            idxxx = target_url.replace("https://www.youtube.com/watch\?v=","")
            #id_cell_title[idxxx] = title_strings
            id_cell_title[idxxx] = current_title[0]

            print()
            print('!!!',title_strings)
            print('@@@',target_url)
            keyword2 = re.search(r'"channelId" content=',html_strings)
            if keyword2 is None:
                pass
            else:
                channelid = keyword2.end(0)
                print("channelId",html_strings[channelid:(channelid + 26)])
                id_cell_1[idxxx] = html_strings[channelid:(channelid + 26)] 
            keyword3 = re.search(r'"datePublished" content=',html_strings)
            if keyword3 is None:
                pass
            else:
                published = keyword3.end(0)
                print("datePublished",html_strings[published:(published + 12)])
            keyword4 = re.search(r'"uploadDate" content=',html_strings)
            if keyword4 is None:
                pass
            else:
                uploaded = keyword4.end(0)
                print("uploadDate",html_strings[uploaded:(uploaded + 12)])
                id_cell_2[idxxx] = html_strings[uploaded:(uploaded + 12)]
            keywords5 = re.search(r'"lengthSeconds":"(\d+)",',html_strings)
            if keywords5 is None:
                pass
            else:
                seconds = keywords5.group(1)
                print("seconds",seconds)
                id_cell_seconds[idxxx] = seconds

            print(current_description[0])
#    for ind,p in enumerate(video_list):
#        print(ind,p)

    return video_list, total_list, id_cell_1, id_cell_2, id_cell_seconds, id_cell_title


def second_gether(words, x, video_list_0, already_list, total_list, id_cell_1, id_cell_2):

    url_list = [ "https://www.youtube.com/watch?v=" + str(x) for x in video_list_0 ]
#    print(video_list_0)
    video_list_0.clear()

    if len(url_list) > 0:
        sum_list = []
        rem = []
        for i,url in enumerate(url_list):
            if not re.match(r'^http',url):
    #        if not re.match(r'^@',url):
                continue
    #        url = url.replace('@ ',"https://www.youtube.com/watch\?v=")

            videoid = url.replace("https://www.youtube.com/watch\?v=","")
            if videoid in id_cell_1:
#                print("----------------")
#                print(x,';',(i + 1),';',"skip  ")
#                print("----------------")
                continue

            if url in already_list:
#                print()
#                print(x,';',(i + 1),';',"skip  ")
#                print(" (not relevant)")
                rem.append(url)
                continue

#            print("----------------")
#            print(x,';',(i + 1),';',url)

            try:
                video_list, total_list, id_cell_1, id_cell_2, id_cell_seconds, id_cell_title = first_gether(words, url, total_list, id_cell_1, id_cell_2)
            except:
                time.sleep(1)
                continue

            already_list.append(url) 

#  l o g
###  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##              
            if videoid in id_cell_1 and videoid in id_cell_2:
                with open('log.txt', 'a') as out:
                    try:
                        out.write( "vi_id: " + videoid + " up_id: " + id_cell_2[videoid] + " ch_id: " + id_cell_1[videoid] + " second: " + id_cell_seconds[videoid] + " title: " + id_cell_title[videoid] + "\n")
                    except:
                        print("file write error")
                    out.close()
            del(id_cell_seconds, id_cell_title) # from first_gether function return values

###  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##  ##              

            if ( len(video_list) > 0 ):
#                video_list = list(set(video_list))
                sum_list.extend(video_list)

        total_list = list(set(total_list))
        if ( len(rem) > 0 ):
            for remove in rem:
                if remove in sum_list:
                    inum = sum_list.index(remove)
                    sum_list.pop(inum)

        new_list = sorted(list(set(sum_list)),key=sum_list.index)

        video_list_0.extend(new_list)
#        for ind,p in enumerate(video_list_0):
#            print(ind,p)

        x = x + 1

        if ( x < 4000 and len(new_list) > 0 ):
            already_list, total_list, id_cell_1, id_cell_2 = second_gether(words, x, video_list_0, already_list, total_list, id_cell_1, id_cell_2)

    return already_list,total_list,id_cell_1,id_cell_2

# top level
counter_x = 0

second_gether(words, counter_x, video_list_0, already_list, total_list, id_cell_1, id_cell_2)
Edit
Pub: 14 Jan 2023 06:17 UTC
Edit: 15 Jan 2023 07:05 UTC
Views: 198