Downloading YouTube Videos with Python

Downloading videos from YouTube can be useful for various reasons, such as watching them offline in areas with unstable internet connections or saving educational materials. In this post, we’ll explore how to download YouTube videos using Python.

Installing Required Libraries

First, we’ll use a library called pytubefix to handle the video downloads from YouTube. This library simplifies the process of downloading YouTube videos. You can install it using the following command

pip install pytubefix

Code Explanation

Here is the Python code to download YouTube videos

from pytubefix import YouTube
from pytubefix.cli import on_progress

def download_video(url, output_path='.'):
    try:
        yt = YouTube(url, on_progress_callback=on_progress)
        stream = yt.streams.filter(file_extension='mp4').get_highest_resolution()
        stream.download(output_path)
        print("Download complete.")
        print(f"Video title: {yt.title}")
    except Exception as e:
        print(f"An error occurred: {e}")

def main():
    url = input("YouTube video URL enter : ")
    output_path = input("video save path : ") or '.'
    download_video(url, output_path)

if __name__ == "__main__":
    main()

This code downloads a video from a YouTube URL provided by the user. It uses the pytubefix library to create a YouTube object, selects the highest resolution mp4 stream, and downloads it. Once the download is complete, it prints “Download complete.” along with the video’s title.

python youtube save the video

How to Run the Code

Save the above code as a Python file, for example, download_youtube.py.Open a terminal or command prompt and navigate to the directory where the file is saved.Run the following command to execute the code

python download_youtube.py

When the program runs, enter the URL of the YouTube video you want to download and specify the path where you want to save it.

Conclusion

In this post, we explored how to download YouTube videos using Python. With the pytubefix library, you can easily download videos with simple code. Feel free to expand on this code to create your own YouTube downloading program with additional features!

By Low ahn

리눅스를 처음 접하시는 분들은 위한 다양한 리눅스 정보를 공유합니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다