python requests download youtube video

How to Download YouTube Videos Using Python Requests Library

Python requests library makes it very easy to download YouTube videos programmatically. Here is how you can download a YouTube video using Python requests library:

Step 1: Install required libraries

You will need to install two libraries, requests and pytube. You can do this using pip:

pip install requests pytube

Step 2: Get the YouTube video URL

You will need to get the URL of the YouTube video you want to download. You can do this by going to the YouTube video, clicking on the share button, and copying the URL.

Step 3: Download the YouTube video

Now that you have the YouTube video URL, you can use Python requests library to download it. Here is how:


import requests
from pytube import YouTube

# Get the YouTube video URL
url = 'https://www.youtube.com/watch?v=9bZkp7q19f0'

# Create a YouTube object
youtube = YouTube(url)

# Get the highest resolution stream
stream = youtube.streams.get_highest_resolution()

# Download the video using requests
response = requests.get(stream.url)
with open('video.mp4', 'wb') as f:
    f.write(response.content)
  

This code will download the YouTube video and save it as video.mp4 in the current directory.

Step 4: Handle errors

There are several things that can go wrong when downloading YouTube videos. For example, the video might not be available in the requested resolution, or the video might be blocked in your region. You should handle these errors appropriately. Here is an example:


try:
    # Get the highest resolution stream
    stream = youtube.streams.get_highest_resolution()
    
    # Download the video using requests
    response = requests.get(stream.url)
    with open('video.mp4', 'wb') as f:
        f.write(response.content)
except Exception as e:
    print(f'Error: {e}')
  

This code will catch any exceptions that occur while downloading the video and print an error message.

Alternative method: Using pytube directly

You can also download YouTube videos using pytube directly, without using requests. Here is how:


from pytube import YouTube

# Get the YouTube video URL
url = 'https://www.youtube.com/watch?v=9bZkp7q19f0'

# Create a YouTube object
youtube = YouTube(url)

# Download the highest resolution video
youtube.streams.get_highest_resolution().download()
  

This code will download the YouTube video and save it in the current directory with the default filename.