使用 Pytube 从 YouTube 下载播放列表

新手上路,请多包涵

我想使用 PyTube 库下载 YouTube 播放列表。目前,我一次只能下载一个视频。我不能一次下载多个视频。

目前,我的实现是

import pytube

link = input('Please enter a url link\n')
yt = pytube.YouTube(link)
stream = yt.streams.first()
finished = stream.download()
print('Download is complete')

这导致以下输出

>> Download is complete

YouTube 文件已下载。当我尝试使用播放列表链接( 示例)时,只会下载第一个视频。没有错误输出。

我希望能够在不重新提示用户的情况下下载整个播放列表。

原文由 Anish Mazumdar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

您可以导入 Playlist 来实现这一点。在 redoc 中没有提到播放列表,尽管在 此处的 GitHub 存储库中有一个部分。脚本的来源在 此处 的回购协议中。

 from pytube import Playlist

playlist = Playlist('https://www.youtube.com/watch?v=58PpYacL-VQ&list=UUd6MoB9NC6uYN2grvUNT-Zg')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
playlist.download_all()

注意:我发现支持方法 Playlist.video_urls 不起作用。然而,视频仍然被下载, 如此处所示

原文由 Glazbee 发布,翻译遵循 CC BY-SA 4.0 许可协议

上述解决方案不再有效。这是下载 Youtube 播放列表中引用的视频的声音流的代码。使用的是 Pytube3,不是 pytube。请注意,播放列表必须公开才能下载成功。另外,如果你想下载完整的视频而不是只下载音轨,你必须修改 Youtube 标签常量的值。空的 Playlist.videos 列表修复取自这篇 Stackoverflow 帖子: PyTube3 Playlist returns empty list

 import re
from pytube import Playlist

YOUTUBE_STREAM_AUDIO = '140' # modify the value to download a different stream
DOWNLOAD_DIR = 'D:\\Users\\Jean-Pierre\\Downloads'

playlist = Playlist('https://www.youtube.com/playlist?list=PLzwWSJNcZTMSW-v1x6MhHFKkwrGaEgQ-L')

# this fixes the empty playlist.videos list
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")

print(len(playlist.video_urls))

for url in playlist.video_urls:
    print(url)

# physically downloading the audio track
for video in playlist.videos:
    audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO)
    audioStream.download(output_path=DOWNLOAD_DIR)

原文由 Jean-Pierre Schnyder 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题