Open In App

Download Video in MP3 format using PyTube

YouTube is the world’s most common video sharing site, and you can experience a situation as a hacker where you want to script something to download videos. For this, We present Pytube to you.

To do our task, we will some libraries especially the pytube from python. For this, we have to import it. To import pytube, we can use the commands according to the python version.



For Python2 : pip install pytube
For Python3 : pip3 install pytube
For pyube3 : pip install pytube3

To save the audio file, we are using the os module and import by using the command given below :

pip install os_sys

Procedure:



Implementation:




# importing packages
from pytube import YouTube
import os
  
# url input from user
yt = YouTube(
    str(input("Enter the URL of the video you want to download: \n>> ")))
  
# extract only audio
video = yt.streams.filter(only_audio=True).first()
  
# check for destination to save file
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
  
# download the file
out_file = video.download(output_path=destination)
  
# save the file
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
  
# result of success
print(yt.title + " has been successfully downloaded.")

Output:

Article Tags :