~/blog/descargar-videos-de-youtube-con-python

Código Completo

·2 min read·

Antes de comenzar, instalaremos las librerías necesarias:

  • pytube: pip install pytube
  • tkinter: pip install tkinter

Importamos la clase YouTube de la librería pytube y todo el módulo tkinter, que se usará para interactuar con videos de YouTube y crear la interfaz gráfica.

from pytube import YouTube
from tkinter import *

Definimos una función llamada actions() que se ejecutará al hacer clic en el botón de descarga. En esta función, obtenemos el enlace del video ingresado por el usuario desde el widget Entry. Luego, creamos una instancia de la clase YouTube con el enlace y obtenemos la mayor resolución disponible. Finalmente, descargamos el video con la configuración especificada.

def actions():
    link = videos.get()
    video = YouTube(link)
    descarga = video.streams.get_highest_resolution()
    descarga.download()

Creamos la ventana principal con la clase Tk y configuramos algunas opciones de apariencia: un borde de 25, ventana no redimensionable, título ("Download videos") e ícono.

root = Tk()
root.config(bd=25)
root.resizable(0, 0)
root.title("Download videos")
root.iconbitmap('./logo-youtube.ico')

Creamos un widget Label en la ventana principal. Este label mostrará el texto "enter the link of the video to download" y se ubicará en la fila 0, columna 1 usando el sistema grid.

instructionText = Label(
    root, text="enter the link of the video to download\n")
instructionText.grid(row=0, column=1)

Creamos un widget Entry donde el usuario puede ingresar el enlace del video. Este widget se ubica en la fila 1, columna 1 dentro de la ventana principal.

videos = Entry(root)
videos.grid(row=1, column=1)

Creamos un widget Button con el texto "Download" que ejecutará la función actions() al hacer clic. El botón se ubica en la fila 2, columna 1.

boton = Button(root, text="Download", command=actions)
boton.grid(row=2, column=1)

Iniciamos el bucle principal de la interfaz gráfica. Esto hace que la ventana principal aparezca y permanezca abierta hasta que el usuario la cierre. Durante este tiempo, la interfaz responderá a las interacciones del usuario, como hacer clic en el botón de descarga.

root.mainloop()

Código Completo

from pytube import YouTube
from tkinter import *

def actions():
    link = videos.get()
    video = YouTube(link)
    descarga = video.streams.get_highest_resolution()
    descarga.download()

root = Tk()
root.config(bd=25)
root.resizable(0, 0)
root.title("Download videos")
root.iconbitmap('./logo-youtube.ico')

instructionText = Label(
    root, text="enter the link of the video to download\n")
instructionText.grid(row=0, column=1)

videos = Entry(root)
videos.grid(row=1, column=1)

boton = Button(root, text="Download", command=actions)
boton.grid(row=2, column=1)

root.mainloop()

¿Te gustó lo que leíste?

Suscríbete para recibir los nuevos posts en tu email.