使用“”后获取标题和urlytsearch:字符串“用python中的youtubedl

2024-09-30 18:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我正在使用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))

Output of previous code

我试图得到视频的标题和实际使用的YouTube网址。当用户自己输入一个实际的URL时,我可以很容易地获得这些信息(如上所示),但是当使用ytsearch:字符串“方法。在

“forcetitle:True”选项将我想要的标题输出到控制台,这样我就知道它在某个地方,我只需要找到一种方法来提取它。至于网页的URL输出,我不确定是否可以通过这种方式获得,因为在搜索第一个结果的情况下,“webpage_URL”输出的所有内容都是返回搜索结果(“ytsearch:橡皮擦f64"). 在

此外,我还添加了选项“'forceurl:True”,以便能够说明forceurl没有输出我要查找的url。我特别寻找youtube页面的url,这样我就可以自动将这首歌添加到自动播放列表中(由于不同的搜索结果可能导致重复,所以不确定最后是否要这样做)。在

请提出建议。在


Tags: theintrueurlfor视频informationyoutube
1条回答
网友
1楼 · 发布于 2024-09-30 18:28:27

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

执行ytsearch:时,应执行以下操作:

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

或者视频的标题:

^{pr2}$

而不是:

infoSearched[str(i)]

我希望这有帮助。在

相关问题 更多 >