Home > Back-end >  How to use python to download youtube videos?
How to use python to download youtube videos?

Time:11-14

Does anyone know how to download youtube videos with python? Ask for help .(just tell me the code)

CodePudding user response:

You can use pytube3.

Start by running pip install pytube3 or pip install pytube in your command prompt/terminal.

Here's some basic code you can run:

from pytube import YouTube


PATH = "path/to/where/you/want/to/save" 

# Link of the video to be downloaded
URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"

yt = YouTube(URL)

mp4files = yt.filter('mp4')


yt.set_filename('Video')


d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution)

d_video.download(PATH)

Explanation:

First we create an object of the YouTube module by passing the link as the parameter. Then, we get the appropriate extension (MP4). We then set the file name. After that, we download the file using the download function.

Make sure you are connected to the internet to download the videos.

CodePudding user response:

Pytube is a library capable of doing that. In case you aren't aware of how to install libraries open your command prompt and use:

pip install pytube

then in a python file use:

from pytube import YouTube
 
# where to save
SAVE_PATH = "C:/"
 
# link of the video to be downloaded
link="https://www.youtube.com/watch?v=something"
 
try:
    # object creation using YouTube
    # which was imported in the beginning
    yt = YouTube(link)
except:
    print("Connection Error") #to handle exception
 
# filters out all the files with "mp4" extension
mp4files = yt.filter('mp4')
 
#to set the name of the file
yt.set_filename('Youtube Video') 
 
# get the video with the extension and
# resolution passed in the get() function
d_video = yt.get(mp4files[-1].extension,mp4files[-1].resolution)
try:
    # downloading the video
    d_video.download(SAVE_PATH)
except:
    print("Some Error!")
print('Task Completed!')
  • Related