How to download YouTube videos in Python?

Here, we will see how we can download YouTube videos using pafy modules in Python?
Submitted by Abhinav Gangrade, on July 12, 2020

Modules used:

In this article, we will use pafy module.

pafy module:
pafy is a python library that is used to retrieve Youtube Content and metadata. We can collect video bit-rate, size, duration, rating, author and we can also convert them into audio and we can download the content in the audio format.

Note: We also have to download youtube_dl for the setup of pafy.

Download pafy and youtube_dl:

  • General Way to Download pafy: pip install pafy
  • General Way to Download youtube_dl: pip install youtube_dl
  • Pycharm Users: You can go to the project interpreter and can install these modules from there.

Some of the functions related to pafy:

  1. video=pafy.new(<url>): This function will take the URL of the youtube video and extract the whole metadata of that video like title, author, stream(audio and video).
  2. video.title: This will return us the title of the video.
  3. video.author: This will return us the name of the author of the video.
  4. v=video.streams: This will return us the video streams with the quality and size.
  5. .download(): This will download the video.

Program:

# importing the module
import pafy

# extracting the data
# enter the url into it
video=pafy.new("https://www.youtube.com/watch?v=cAQVYXwiWi0")

# print the title
print(video.title)
# print the author
print(video.author)
# print the duration
print(video.duration)
# print the rating
print(video.rating)
# Getting the stream
# this fumction return us list
stream=video.streams
for i in stream:
    print(i)
# getting audio streams
audio_stream=video.audiostreams
for i in audio_stream:
    print(i)

# get the best video
best_video=video.getbest()
print(best_video)

# get the best audio
best_audio=video.getbestaudio()
print(best_audio)

# Now download the things
# if want to download best video
best_video.download()
# for best audio
best_audio.download()
# now from the streams
stream[0].download()

Output:

SickFlip & Ritviz - Roshni feat. Seedhe Maut
RITVIZ
00:03:06
4.8426752
normal:mp4@640x360
audio:webm@50k
audio:webm@70k
audio:m4a@128k
audio:webm@160k
normal:mp4@640x360
audio:webm@160k

The downloaded will get saved in the same directory in which your Python file is.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.