Script Python para descargar Youtube

descargar Youtube Python

Aplicación para escritorio con Python y Tkinter para descargar desde Youtube en MacOS

Hay veces que necesitamos descargar videos desde Youtube para poder verlos offline, o quizás para conservarlos y tenemos que buscar una página para descargarlos. Y no solo buscar la página sino, a veces, tener que aguantar varias páginas de publicidad.
Este es un script que funciona en la consola, en primera instancia y en el que el único parámetro que tenemos que modificar es en la línea 9 la variable save_path que se encarga de guardar la ubicación donde se guardará nuestro vídeo descargado.

Hay que tener en cuenta que tenemos que importar las librerías tkinter y pytube.

Para ejecutar el script, desde la terminal, simplemente escribir python3 nombre_script.py. Se nos abrirá una ventana y en ella podemos poner la URL del vídeo de Youtube a descargar.

import tkinter as tk
from tkinter import ttk
from pytube import YouTube
import threading
import os

def download_video():
    video_url = entry.get()
    save_path = "/Users/nombre/Downloads/"  # insert path where you want to save the video

    try:
        # Create a YouTube object
        yt = YouTube(video_url)
        # Get the highest resolution stream
        video_stream = yt.streams.get_highest_resolution()

        # Disable the download button
        button.config(state=tk.DISABLED)

        # Create a progress bar and label
        progress_label = tk.Label(window, text="Downloading...")
        progress_label.pack()
        progress_bar = ttk.Progressbar(window, orient=tk.HORIZONTAL, length=300, mode='indeterminate')
        progress_bar.pack()

        # Start the download in a separate thread
        download_thread = threading.Thread(target=perform_download, args=(video_stream, save_path, progress_bar))
        download_thread.start()
    except Exception as e:
        print("Error:", str(e))
        status_label.config(text="Error: " + str(e))

def perform_download(video_stream, save_path, progress_bar):
    # Start the progress bar animation
    progress_bar.start()

    try:
        # Download the video
        video_filename = video_stream.default_filename
        save_location = os.path.join(save_path, video_filename)
        video_stream.download(output_path=save_path, filename=video_filename)
        print("Download completed!")
        status_label.config(text="Download completed!")
    except Exception as e:
        print("Error:", str(e))
        status_label.config(text="Error: " + str(e))

    # Stop the progress bar animation
    progress_bar.stop()

    # Enable the download button
    button.config(state=tk.NORMAL)

# Create the main window
window = tk.Tk()
window.title("YouTube Video Downloader")

# Set the dimensions of the window
window_width = 400
window_height = 250
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x_coordinate = int((screen_width / 2) - (window_width / 2))
y_coordinate = int((screen_height / 2) - (window_height / 2))
window.geometry(f"{window_width}x{window_height}+{x_coordinate}+{y_coordinate}")

# Create the input label and entry
label = tk.Label(window, text="Enter YouTube video URL:")
label.pack()
entry = tk.Entry(window)
entry.pack()

# Create the download button
button = tk.Button(window, text="Download", command=download_video)
button.pack()

# Create the status label
status_label = tk.Label(window, text="")
status_label.pack()

# Start the Tkinter event loop
window.mainloop()

Aplicación gráfica para escritorio para descargar desde Youtube

Si queremos crear una pequeña aplicación gráfica que podamos ejecutar sin tener que invocarla a través de la consola podemos seguir los siguientes pasos:

  1. Instalamos pyinstaller si previamente no lo tenemos.
pip install pyinstaller
  1. En el mismo directorio donde tenemos nuestro script ejecutamos:
pyinstaller --onefile --windowed nombre_script.py

Nos creará un directorio llamado dist donde nos habrá creado la aplicación llamada nombre_script.app para MacOS.
Para ejecutarla lo haremos como cualquier otro programa que tengamos instalado.

Sobre mi

Trabajo en el desarrollo de webs profesionales desde hace más de 25 años.
También me dedico a mis proyectos personales.

Últimas notas publicadas

Categorías

Scroll al inicio