使用 youtube-dl 搜索 Youtube 视频 [英] Searching Youtube videos using youtube-dl
本文介绍了使用 youtube-dl 搜索 Youtube 视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个 Discord Music Bot,我需要使用用户提供的关键字搜索 YouTube.目前我知道如何通过网址播放.
I am trying to build a Discord Music Bot and I need to search the YouTube using keywords given by the user. Currently I know how to play from a 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)
推荐答案
Youtube_DL 有一个 extract_info
方法可供您使用.而不是给它一个链接,你只需要像这样传递 ytsearch:args
:
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:
- 它适用于单词和网址
- 如果您进行 YouTube 搜索,输出将是一个字典列表.在这种情况下,它将返回第一个结果
- 它将返回一个包含以下信息的字典:
- 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'],
}
这篇关于使用 youtube-dl 搜索 Youtube 视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文