使用youtube-dl搜索Youtube视频

3

我正在尝试构建一个Discord音乐机器人,需要使用用户提供的关键词搜索YouTube。目前我知道如何通过URL播放。

       loop = loop or asyncio.get_event_loop()
       data = await loop.run_in_executor( None, lambda: ytdl.extract_info(url, download=not stream))
       if "entries" in data:
            data = data["entries"][0]

        filename = data["url"] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
2个回答

9

Youtube_DL有一个名为extract_info的方法,您可以使用它。您无需提供链接,只需传递ytsearch:args即可:

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

这个函数有几个重要的事项:

  • 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'],
    }
    

无法工作:ModuleNotFoundError: 找不到模块 'youtube_dl' - Emmanuel Goldstein
您是否安装了正确的软件包?这个答案也可能已经过时了,因为youtube-dl的最新版本是2021年发布的。 - MrSpaar

0

我不确定使用youtube-dl通过关键词搜索YouTube URL是否好用。你可能应该看一下youtube-search


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接