1- import copy
21import json
2+ import copy
33from typing import Union
44from urllib .parse import urlencode
55
6-
76from youtubesearchpython .core .requests import RequestCore
87from youtubesearchpython .handlers .componenthandler import ComponentHandler
98from youtubesearchpython .handlers .requesthandler import RequestHandler
@@ -30,27 +29,17 @@ def sync_create(self):
3029 self ._parseSource ()
3130
3231 def _getRequestBody (self ):
33- requestBody = copy .deepcopy (RequestPayload )
34-
35- # place query at top level
36- requestBody ['query' ] = self .query if self .query is not None else ''
37-
38- # put hl/gl into the existing context.client (not as a top-level "client")
39- context = requestBody .setdefault ('context' , {})
40- client = context .setdefault ('client' , {})
41- client .update ({
42- 'hl' : self .language or client .get ('hl' ),
43- 'gl' : self .region or client .get ('gl' ),
44- })
45-
32+ ''' Fixes #47 '''
33+ requestBody = copy .deepcopy (requestPayload )
34+ requestBody ['query' ] = self .query
35+ requestBody ['client' ] = {
36+ 'hl' : self .language ,
37+ 'gl' : self .region ,
38+ }
4639 if self .searchPreferences :
4740 requestBody ['params' ] = self .searchPreferences
4841 if self .continuationKey :
4942 requestBody ['continuation' ] = self .continuationKey
50-
51- if not searchKey :
52- raise Exception ('INNERTUBE API key (searchKey) is not set.' )
53-
5443 self .url = 'https://www.youtube.com/youtubei/v1/search' + '?' + urlencode ({
5544 'key' : searchKey ,
5645 })
@@ -61,24 +50,36 @@ def _makeRequest(self) -> None:
6150 request = self .syncPostRequest ()
6251 try :
6352 self .response = request .text
64- except Exception :
53+ except :
6554 raise Exception ('ERROR: Could not make request.' )
6655
6756 async def _makeAsyncRequest (self ) -> None :
6857 self ._getRequestBody ()
6958 request = await self .asyncPostRequest ()
7059 try :
7160 self .response = request .text
72- except Exception :
61+ except :
7362 raise Exception ('ERROR: Could not make request.' )
7463
7564 def result (self , mode : int = ResultMode .dict ) -> Union [str , dict ]:
65+ '''Returns the search result.
66+ Args:
67+ mode (int, optional): Sets the type of result. Defaults to ResultMode.dict.
68+ Returns:
69+ Union[str, dict]: Returns JSON or dictionary.
70+ '''
7671 if mode == ResultMode .json :
7772 return json .dumps ({'result' : self .resultComponents }, indent = 4 )
7873 elif mode == ResultMode .dict :
7974 return {'result' : self .resultComponents }
8075
8176 def _next (self ) -> bool :
77+ '''Gets the subsequent search result. Call result
78+ Args:
79+ mode (int, optional): Sets the type of result. Defaults to ResultMode.dict.
80+ Returns:
81+ Union[str, dict]: Returns True if getting more results was successful.
82+ '''
8283 if self .continuationKey :
8384 self .response = None
8485 self .responseSource = None
@@ -111,13 +112,12 @@ def _getComponents(self, findVideos: bool, findChannels: bool, findPlaylists: bo
111112 if playlistElementKey in element .keys () and findPlaylists :
112113 self .resultComponents .append (self ._getPlaylistComponent (element ))
113114 if shelfElementKey in element .keys () and findVideos :
114- shelf = self ._getShelfComponent (element )
115- for shelfElement in shelf .get ('elements' , []):
115+ for shelfElement in self ._getShelfComponent (element )['elements' ]:
116116 self .resultComponents .append (
117- self ._getVideoComponent (shelfElement , shelfTitle = shelf .get ('title' ))
118- )
117+ self ._getVideoComponent (shelfElement , shelfTitle = self ._getShelfComponent (element )['title' ]))
119118 if richItemKey in element .keys () and findVideos :
120- richItemElement = self ._getValue (element , [richItemKey , 'content' ]) or {}
119+ richItemElement = self ._getValue (element , [richItemKey , 'content' ])
120+ ''' Initial fallback handling for VideosSearch '''
121121 if videoElementKey in richItemElement .keys ():
122122 videoComponent = self ._getVideoComponent (richItemElement )
123123 self .resultComponents .append (videoComponent )
0 commit comments