在python中使用带有youtube-dl的"ytsearch:string"后获取标题和url



我一直在研究一个 Discord 音乐机器人,它几乎完成了。我还有两件事要弄清楚(它们背后有同样的想法(。

我正在使用youtube_dl下载视频,我最近发现有一种方法可以从 youtube 中搜索和获取顶部搜索结果并播放它,允许我的 discord 频道上的用户通过输入他们记得的几个单词来播放歌曲。当我尝试获取搜索顶部结果时将要播放的 youtube 视频的标题时,问题就来了。

下面我包含了一些代码,这些代码简单地显示了我的意思,以及我目前正在使用的内容(如果有更好的方法来执行我试图弄清楚的任务,请随时为我指明方向(。

import youtube_dl
ydl_opts = {
'quiet': True,
'skip_download': True,
'forcetitle': True,
'forceurl': True,
}
# Extracts information using the "ytsearch:string" method
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
infoSearched = ydl.extract_info("ytsearch:eraser f64")
# Print the available keys
print('n keys available: n')
for i in infoSearched:
print(i)
# Output the information that has potential to be what I am looking for
for i in infoSearched:
if i is 'webpage_url' or i is 'webpage_url_basename':
print('n {}    {}' .format(infoSearched[str(i)], i))
for i in range(2):
print("n")
# Extracts information using the actual URL method
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
infoUrlGiven = ydl.extract_info("https://www.youtube.com/watch?v=pb2fwx4O_Ks")
# Outputs the correct information I am looking for
for i in infoUrlGiven:
if i is 'webpage_url' or i is 'title':
print('n {}    {}' .format(infoUrlGiven[str(i)], i))

先前代码的输出

我正在尝试获取视频的标题和正在使用的实际YouTube网址。当用户自己输入实际URL时,我能够轻松获得该信息(如上所示(,但是我不确定在使用" ytsearch:string"方法查找视频时如何提取信息。

"'forcetitle':True"选项将我想要的标题输出到控制台,所以我知道它在某个地方,我只需要找到一种方法来提取它。至于webpage_URL输出,我不确定我是否可以以这种方式实际获得它,因为在搜索第一个结果的情况下,"webpage_url"输出的所有内容都是返回搜索("ytsearch:eraser f64"(。

此外,我还包括选项"'forceurl':True",以便能够说forceurl没有输出我正在寻找的url。我专门寻找 youtube 页面的网址,以便我可以自动将歌曲添加到自动播放列表中(由于不同的搜索结果可能导致重复,不确定我最终是否要这样做(。

请指教。

我认为当您使用 ytsearch: 执行extract_info时,它会返回与使用字符串的 url 执行extract_info不同的信息字典。

执行 ytsearch: 时,您将执行以下操作:

infosearched['entries'][0]['webpage_url']

或者对于视频的标题:

infosearched['entries'][0]['title']

而不是:

infoSearched[str(i)]

我希望这有所帮助。

最新更新