@@ -4,7 +4,7 @@
44"""
55
66from functools import reduce
7−from json import loads
7+from json import loads, dumps
88from urllib.parse import quote_plus
99
1010# about
@@ -20,12 +20,15 @@ about = {
2020# engine dependent config
2121categories = ['videos', 'music']
2222paging = True
23+language_support = False
2324time_range_support = True
2425
2526# search-url
2627base_url = 'https://www.youtube.com/results'
2728search_url = base_url + '?search_query={query}&page={page}'
2829time_range_url = '&sp=EgII{time_range}%253D%253D'
30+# the key seems to be constant
31+next_page_url = 'https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
2932time_range_dict = {'day': 'Ag',
3033 'week': 'Aw',
3134 'month': 'BA',
@@ -40,21 +43,73 @@ base_youtube_url = 'https://www.youtube.com/watch?v='
4043
4144# do search-request
4245def request(query, params):
43− params['url'] = search_url.format(query=quote_plus(query),
44− page=params['pageno'])
45− if params['time_range'] in time_range_dict:
46− params['url'] += time_range_url.format(time_range=time_range_dict[params['time_range']])
46+ if not params['engine_data'].get('next_page_token'):
47+ params['url'] = search_url.format(query=quote_plus(query), page=params['pageno'])
48+ if params['time_range'] in time_range_dict:
49+ params['url'] += time_range_url.format(time_range=time_range_dict[params['time_range']])
50+ else:
51+ print(params['engine_data']['next_page_token'])
52+ params['url'] = next_page_url
53+ params['method'] = 'POST'
54+ params['data'] = dumps({
55+ 'context': {"client": {"clientName": "WEB", "clientVersion": "2.20210310.12.01"}},
56+ 'continuation': params['engine_data']['next_page_token'],
57+ })
58+ params['headers']['Content-Type'] = 'application/json'
4759
4860 return params
4961
5062
5163# get response from search-request
5264def response(resp):
65+ if resp.search_params.get('engine_data'):
66+ return parse_next_page_response(resp.text)
67+ return parse_first_page_response(resp.text)
68+
69+
70+def parse_next_page_response(response_text):
5371 results = []
72+ result_json = loads(response_text)
73+ with open("/tmp/x", "w") as f:
74+ f.write(response_text)
75+ for section in (result_json['onResponseReceivedCommands'][0]
76+ .get('appendContinuationItemsAction')['continuationItems'][0]
77+ .get('itemSectionRenderer')['contents']):
78+ if 'videoRenderer' not in section:
79+ continue
80+ section = section['videoRenderer']
81+ content = "-"
82+ if 'descriptionSnippet' in section:
83+ content = ' '.join(x['text'] for x in section['descriptionSnippet']['runs'])
84+ results.append({
85+ 'url': base_youtube_url + section['videoId'],
86+ 'title': ' '.join(x['text'] for x in section['title']['runs']),
87+ 'content': content,
88+ 'author': section['ownerText']['runs'][0]['text'],
89+ 'length': section['lengthText']['simpleText'],
90+ 'template': 'videos.html',
91+ 'embedded': embedded_url.format(videoid=section['videoId']),
92+ 'thumbnail': section['thumbnail']['thumbnails'][-1]['url'],
93+ })
94+ try:
95+ token = result_json['onResponseReceivedCommands'][0]\
96+ .get('appendContinuationItemsAction')['continuationItems'][1]\
97+ .get('continuationItemRenderer')['continuationEndpoint']\
98+ .get('continuationCommand')['token']
99+ results.append({
100+ "engine_data": token,
101+ "key": "next_page_token",
102+ })
103+ except:
104+ pass
105+
106+ return results
54107
55− results_data = resp.text[resp.text.find('ytInitialData'):]
56− results_data = results_data[results_data.find('{'):results_data.find(';</script>')]
57108
109+def parse_first_page_response(response_text):
110+ results = []
111+ results_data = response_text[response_text.find('ytInitialData'):]
112+ results_data = results_data[results_data.find('{'):results_data.find(';</script>')]
58113 results_json = loads(results_data) if results_data else {}
59114 sections = results_json.get('contents', {})\
60115 .get('twoColumnSearchResultsRenderer', {})\
@@ -63,6 +118,16 @@ def response(resp):
63118 .get('contents', [])
64119
65120 for section in sections:
121+ if "continuationItemRenderer" in section:
122+ next_page_token = section["continuationItemRenderer"]\
123+ .get("continuationEndpoint", {})\
124+ .get("continuationCommand", {})\
125+ .get("token", "")
126+ if next_page_token:
127+ results.append({
128+ "engine_data": next_page_token,
129+ "key": "next_page_token",
130+ })
66131 for video_container in section.get('itemSectionRenderer', {}).get('contents', []):
67132 video = video_container.get('videoRenderer', {})
68133 videoid = video.get('videoId')