使用Python下载 Youtube 视频或整个播放列表
先决条件:
- 特金特
- 知乎
- pytube
- Tkinter 中的线程
- YouTube API
Python为开发 GUI(图形用户界面)提供了多种选择。在所有 GUI 方法中,Tkinter 是最常用的方法。这是一个标准的Python接口,附带的Python Tk的GUI工具包。 Python with Tkinter 是创建 GUI 应用程序的最快、最简单的方法。
在本文中,我们将讨论如何使用Python创建一个 GUI 应用程序来下载 YouTube 视频或完整的 YouTube 播放列表。
在我们开始之前,我们将讨论pyyoutube模块。 pyyoutube模块提供了一种使用 YouTube 数据 API V3 的简单方法。
安装:
pip install python-youtube
从 YouTube 播放列表下载选定的视频
在本节中,我们将学习如何使用Python的Tkinter 从 YouTube 播放列表中仅下载选定的视频。
方法:
- 首先,我们将使用pyyoutube模块从 YouTube 播放列表中获取所有视频链接。
- 然后我们将选择我们要下载的视频链接。
- 然后我们将使用pytube模块一一下载每个视频。
下面是 GUI 的样子:
让我们一步一步地理解实现:
- 创建一个 Tkinter 窗口并添加按钮、标签、滚动条等...
Python3
# Import Required Modules
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x400')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
# Add Button
get_videos = Button(root, text="Get Videos")
get_videos.pack(pady=10)
# Add Scollbar
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=BOTH)
list_box = Listbox(root, selectmode="multiple")
list_box.pack(expand=YES, fill="both")
list_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_box.yview)
download_start = Button(root, text="Download Start", state=DISABLED)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
Python3
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
Python3
# Import Required Modules
from tkinter import *
from pyyoutube import Api
from pytube import YouTube
from threading import Thread
from tkinter import messagebox
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
# Create Object
root = Tk()
# Set geometry
root.geometry('400x400')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
# Add Button
get_videos = Button(root, text="Get Videos", command=get_list_videos)
get_videos.pack(pady=10)
# Add Scollbar
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=BOTH)
list_box = Listbox(root, selectmode="multiple")
list_box.pack(expand=YES, fill="both")
list_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_box.yview)
download_start = Button(root, text="Download Start",
command=threading, state=DISABLED)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
Python3
# Import Required Modules
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x200')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
download_start = Button(root, text="Download Start")
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
Python3
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links
for index, videoid in enumerate(playlist_item_by_id['items']):
link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
print(f"Downloaded:- {link}")
messagebox.showinfo("Success", "Video Successfully downloaded")
Python3
# Import Required Modules
from tkinter import *
from pyyoutube import Api
from pytube import YouTube
from threading import Thread
from tkinter import messagebox
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links
for index, videoid in enumerate(playlist_item_by_id['items']):
link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
print(f"Downloaded:- {link}")
messagebox.showinfo("Success", "Video Successfully downloaded")
# Create Object
root = Tk()
# Set geometry
root.geometry('400x200')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
download_start = Button(root, text="Download Start", command=threading)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
- 现在我们将创建三个函数:
- get_list_videos:-它将提供 YouTube 播放列表的所有视频链接的列表。
- 线程:-用于 Tkinter 中的线程。
- download_videos:-用于下载 YouTube 视频。
蟒蛇3
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
下面是完整的实现:
蟒蛇3
# Import Required Modules
from tkinter import *
from pyyoutube import Api
from pytube import YouTube
from threading import Thread
from tkinter import messagebox
def get_list_videos():
global playlist_item_by_id
# Clear ListBox
list_box.delete(0, 'end')
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links and insert into listbox
for index, videoid in enumerate(playlist_item_by_id['items']):
list_box.insert(
END, f" {str(index+1)}. {videoid['contentDetails']['videoId']}")
download_start.config(state=NORMAL)
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
download_start.config(state="disabled")
get_videos.config(state="disabled")
# Iterate through all selected videos
for i in list_box.curselection():
videoid = playlist_item_by_id['items'][i]['contentDetails']['videoId']
link = f"https://www.youtube.com/watch?v={videoid}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
messagebox.showinfo("Success", "Video Successfully downloaded")
download_start.config(state="normal")
get_videos.config(state="normal")
# Create Object
root = Tk()
# Set geometry
root.geometry('400x400')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
# Add Button
get_videos = Button(root, text="Get Videos", command=get_list_videos)
get_videos.pack(pady=10)
# Add Scollbar
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=BOTH)
list_box = Listbox(root, selectmode="multiple")
list_box.pack(expand=YES, fill="both")
list_box.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=list_box.yview)
download_start = Button(root, text="Download Start",
command=threading, state=DISABLED)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
输出:
下载完整的 YouTube 播放列表
在这里,我们将学习如何使用Python在 Tkinter 中下载完整的 YouTube 播放列表。
方法:
- 首先,我们将使用pyyoutube模块从 YouTube 播放列表中获取所有视频链接。
- 然后我们将遍历所有视频并使用pytube模块一个一个下载每个视频。
下面是 GUI 的样子:
让我们一步一步地理解实现:
- 创建一个 Tkinter 窗口并添加按钮、标签等...
蟒蛇3
# Import Required Modules
from tkinter import *
# Create Object
root = Tk()
# Set geometry
root.geometry('400x200')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
download_start = Button(root, text="Download Start")
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
- 现在我们将创建两个函数:
- 线程:-用于 Tkinter 中的线程。
- download_videos:-用于下载 YouTube 视频。
蟒蛇3
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links
for index, videoid in enumerate(playlist_item_by_id['items']):
link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
print(f"Downloaded:- {link}")
messagebox.showinfo("Success", "Video Successfully downloaded")
下面是完整的实现:
蟒蛇3
# Import Required Modules
from tkinter import *
from pyyoutube import Api
from pytube import YouTube
from threading import Thread
from tkinter import messagebox
def threading():
# Call download_videos function
t1 = Thread(target=download_videos)
t1.start()
def download_videos():
# Create API Object
api = Api(api_key='Enter API Key')
if "youtube" in playlistId.get():
playlist_id = playlistId.get()[len(
"https://www.youtube.com/playlist?list="):]
else:
playlist_id = playlistId.get()
# Get list of video links
playlist_item_by_id = api.get_playlist_items(
playlist_id=playlist_id, count=None, return_json=True)
# Iterate through all video links
for index, videoid in enumerate(playlist_item_by_id['items']):
link = f"https://www.youtube.com/watch?v={videoid['contentDetails']['videoId']}"
yt_obj = YouTube(link)
filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')
# download the highest quality video
filters.get_highest_resolution().download()
print(f"Downloaded:- {link}")
messagebox.showinfo("Success", "Video Successfully downloaded")
# Create Object
root = Tk()
# Set geometry
root.geometry('400x200')
# Add Label
Label(root, text="Youtube Playlist Downloader",
font="italic 15 bold").pack(pady=10)
Label(root, text="Enter Playlist URL:-", font="italic 10").pack()
# Add Entry box
playlistId = Entry(root, width=60)
playlistId.pack(pady=5)
download_start = Button(root, text="Download Start", command=threading)
download_start.pack(pady=10)
# Execute Tkinter
root.mainloop()
输出: