How to download youTube videos? - A tool of python is found in this post
How to Download YouTube Videos with a Simple Python Program
Downloading YouTube videos can be useful when you want to save a video that you own, content you have permission to use, or media that is available for download. For this reason, you can create a simple Python program that makes the process much easier.
Our program uses yt-dlp, a powerful tool for retrieving media from various online services. Instead of requiring users to work with terminal commands, the program provides a simple interface where they only need to enter the video link.
How Does It Work?
The user enters the video URL into the appropriate field and selects the desired quality. The program can use the best available quality or limit the download to 1080p, 720p, or 480p.
There is also an option to download only the audio and save it as an MP3 file. The folder where the file will be saved can be selected directly from the program.
During the download, the program displays the progress, transfer speed, and estimated remaining time. When the process is complete, the user receives a notification that the file has been saved.
What Do You Need?
To use the project, you need to have Python installed on your computer. Then install the required library with:
pip install -U yt-dlp
For some video formats, FFmpeg may also be required, especially when the video and audio are downloaded separately and need to be merged.
Why Create a Tool Like This?
A graphical interface is easier for users who don't want to work with the terminal. Instead of entering long commands, they can paste the link, choose the quality, and simply click one button.
The program can also be expanded with features such as download history, MP4/WebM format selection, multiple simultaneous downloads, and a more advanced progress system.
The tool should only be used for content that you have the legal right or permission to download and use. Always respect the platform's terms of service and the copyright rights of content creators.
Thanks guys for reading this article, please notice that this is for educational purposes only. Thanks in advance.
////////////////////////////////////////////////////////////////////////////////////////////
import os
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
try:
import yt_dlp
except ImportError:
yt_dlp = None
class YouTubeDownloader:
def __init__(self, root):
self.root = root
self.root.title("YouTube Video Downloader")
self.root.geometry("650x430")
self.root.minsize(600, 400)
self.url_var = tk.StringVar()
self.folder_var = tk.StringVar(
value=os.path.join(
os.path.expanduser("~"),
"Downloads"
)
)
self.quality_var = tk.StringVar(
value="Best available"
)
self.status_var = tk.StringVar(
value="Ready"
)
self.progress_var = tk.DoubleVar(
value=0
)
self.create_interface()
# ---------------------------------------------------------
# INTERFACE
# ---------------------------------------------------------
def create_interface(self):
main = ttk.Frame(
self.root,
padding=25
)
main.pack(
fill="both",
expand=True
)
title = ttk.Label(
main,
text="YouTube Video Downloader",
font=("Segoe UI", 20, "bold")
)
title.pack(
anchor="w",
pady=(0, 20)
)
# URL
ttk.Label(
main,
text="YouTube URL:"
).pack(
anchor="w"
)
url_frame = ttk.Frame(main)
url_frame.pack(
fill="x",
pady=(6, 18)
)
self.url_entry = ttk.Entry(
url_frame,
textvariable=self.url_var
)
self.url_entry.pack(
side="left",
fill="x",
expand=True
)
self.url_entry.focus()
# Folder
ttk.Label(
main,
text="Save folder:"
).pack(
anchor="w"
)
folder_frame = ttk.Frame(main)
folder_frame.pack(
fill="x",
pady=(6, 18)
)
self.folder_entry = ttk.Entry(
folder_frame,
textvariable=self.folder_var
)
self.folder_entry.pack(
side="left",
fill="x",
expand=True
)
ttk.Button(
folder_frame,
text="Browse",
command=self.select_folder
).pack(
side="left",
padx=(8, 0)
)
# Quality
ttk.Label(
main,
text="Quality:"
).pack(
anchor="w"
)
self.quality_combo = ttk.Combobox(
main,
textvariable=self.quality_var,
state="readonly",
values=[
"Best available",
"1080p or lower",
"720p or lower",
"480p or lower",
"Audio only (MP3)"
]
)
self.quality_combo.pack(
fill="x",
pady=(6, 20)
)
# Download button
self.download_button = ttk.Button(
main,
text="DOWNLOAD",
command=self.start_download
)
self.download_button.pack(
fill="x",
ipady=8
)
# Progress
self.progress = ttk.Progressbar(
main,
variable=self.progress_var,
maximum=100
)
self.progress.pack(
fill="x",
pady=(25, 8)
)
# Status
self.status_label = ttk.Label(
main,
textvariable=self.status_var
)
self.status_label.pack(
anchor="w"
)
# Info
info = ttk.Label(
main,
text=(
"Use this application only for content you are "
"legally allowed to download."
),
foreground="#666666"
)
info.pack(
anchor="w",
pady=(25, 0)
)
# ---------------------------------------------------------
# SELECT FOLDER
# ---------------------------------------------------------
def select_folder(self):
folder = filedialog.askdirectory(
initialdir=self.folder_var.get()
)
if folder:
self.folder_var.set(folder)
# ---------------------------------------------------------
# START DOWNLOAD
# ---------------------------------------------------------
def start_download(self):
if yt_dlp is None:
messagebox.showerror(
"Missing yt-dlp",
(
"yt-dlp is not installed.\n\n"
"Open Command Prompt and run:\n\n"
"pip install -U yt-dlp"
)
)
return
url = self.url_var.get().strip()
folder = self.folder_var.get().strip()
quality = self.quality_var.get()
if not url:
messagebox.showwarning(
"Missing URL",
"Please paste a YouTube URL."
)
return
if not folder:
messagebox.showwarning(
"Missing folder",
"Please choose a folder."
)
return
try:
os.makedirs(
folder,
exist_ok=True
)
except Exception as error:
messagebox.showerror(
"Folder error",
str(error)
)
return
self.download_button.config(
state="disabled"
)
self.progress_var.set(0)
self.status_var.set(
"Starting download..."
)
thread = threading.Thread(
target=self.download_video,
args=(
url,
folder,
quality
),
daemon=True
)
thread.start()
# ---------------------------------------------------------
# DOWNLOAD
# ---------------------------------------------------------
def download_video(
self,
url,
folder,
quality
):
try:
if quality == "Best available":
format_string = (
"bv*+ba/b"
)
elif quality == "1080p or lower":
format_string = (
"bv*[height<=1080]+ba/"
"b[height<=1080]"
)
elif quality == "720p or lower":
format_string = (
"bv*[height<=720]+ba/"
"b[height<=720]"
)
elif quality == "480p or lower":
format_string = (
"bv*[height<=480]+ba/"
"b[height<=480]"
)
else:
format_string = "ba/b"
output_template = os.path.join(
folder,
"%(title)s.%(ext)s"
)
options = {
"format": format_string,
"outtmpl": output_template,
"progress_hooks": [
self.progress_hook
],
"noplaylist": True,
"quiet": True,
"no_warnings": True,
"merge_output_format": "mp4"
}
# MP3
if quality == "Audio only (MP3)":
options["format"] = "ba/b"
options["postprocessors"] = [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "192"
}
]
with yt_dlp.YoutubeDL(
options
) as downloader:
downloader.download(
[url]
)
self.root.after(
0,
self.download_finished
)
except Exception as error:
self.root.after(
0,
self.download_failed,
str(error)
)
# ---------------------------------------------------------
# PROGRESS
# ---------------------------------------------------------
def progress_hook(self, data):
status = data.get(
"status"
)
if status == "downloading":
total = (
data.get("total_bytes")
or
data.get("total_bytes_estimate")
)
downloaded = data.get(
"downloaded_bytes",
0
)
if total:
percentage = (
downloaded / total
) * 100
self.root.after(
0,
self.progress_var.set,
percentage
)
speed = data.get(
"_speed_str",
""
)
eta = data.get(
"_eta_str",
""
)
status_text = (
f"Downloading... "
f"{speed} | ETA: {eta}"
)
self.root.after(
0,
self.status_var.set,
status_text
)
elif status == "finished":
self.root.after(
0,
self.progress_var.set,
100
)
self.root.after(
0,
self.status_var.set,
"Processing file..."
)
# ---------------------------------------------------------
# SUCCESS
# ---------------------------------------------------------
def download_finished(self):
self.download_button.config(
state="normal"
)
self.progress_var.set(
100
)
self.status_var.set(
"Download complete!"
)
messagebox.showinfo(
"Download complete",
"The video has been downloaded successfully."
)
# ---------------------------------------------------------
# ERROR
# ---------------------------------------------------------
def download_failed(
self,
error
):
self.download_button.config(
state="normal"
)
self.status_var.set(
"Download failed."
)
self.progress_var.set(
0
)
messagebox.showerror(
"Download error",
(
"The video could not be downloaded.\n\n"
f"Details:\n{error}"
)
)
# =============================================================
# MAIN
# =============================================================
def main():
root = tk.Tk()
try:
style = ttk.Style()
style.theme_use(
"vista"
)
except tk.TclError:
pass
YouTubeDownloader(
root
)
root.mainloop()
if __name__ == "__main__":
main()
/////////////////////////////////////////////////////////////////////////////////////

Comments
Post a Comment