Youtube_DL has a extract_info
method that you can use. Instead of giving it a link, you just have to pass ytsearch:args
like so:
from requests import get
from youtube_dl import YoutubeDL
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist':'True'}
def search(arg):
with YoutubeDL(YDL_OPTIONS) as ydl:
try:
get(arg)
except:
video = ydl.extract_info(f"ytsearch:{arg}", download=False)['entries'][0]
else:
video = ydl.extract_info(arg, download=False)
return video
A few important things with this function:
- It works with both words and urls
- If you make a youtube search, the output will be a list a dictionnaries. In this case, it will return the first result
- It will return a dictionnary containing the following informations:
video_infos = search("30 sec video")
#Doesn't contain all the data, some keys are not very important
cleared_data = {
'channel': video['uploader'],
'channel_url': video['uploader_url'],
'title': video['title'],
'description': video['description'],
'video_url': video['webpage_url'],
'duration': video['duration'], #in seconds
'upload_date': video['upload_data'], #YYYYDDMM
'thumbnail': video['thumbnail'],
'audio_source': video['formats'][0]['url'],
'view_count': video['view_count'],
'like_count': video['like_count'],
'dislike_count': video['dislike_count'],
}