9/22/2023

Download Youtube Video, url to local video file.

The code need to install two YouTube downloader package.

Those are pytube, youtube_dl.

This code try to use one of them because sometime it's fail in certain library.


Enjoy code:

.

import ssl
from pytube import YouTube
import youtube_dl

#pip install pytube
#pip install youtube_dl


def configure_ssl():
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = _create_unverified_https_context

def pytube_download(video_url):
try:
yt = YouTube(video_url)
video = yt.streams.get_highest_resolution()
print(f"Downloading: {video.title}")
video.download()
print("Video downloaded successfully using pytube.")
return True
except Exception as e:
print(f"An error occurred while downloading the video with pytube: {e}")
return False

def download_youtube_video(video_url):
download_options = {
'format': 'best',
'outtmpl': '%(title)s-%(id)s.%(ext)s', # Set the output filename format
'progress_hooks': [hook],
}

try:
with youtube_dl.YoutubeDL(download_options) as ydl:
ydl.download([video_url])
print("Video downloaded successfully using youtube-dl.")
except Exception as e:
print(f"An error occurred while downloading the video with youtube-dl: {e}")

def hook(d):
if d['status'] == 'downloading':
print(d['_percent_str'], end="\r")

def main(video_url):
configure_ssl()
if not pytube_download(video_url):
download_youtube_video(video_url)

# Example usage:
if __name__ == "__main__":
video_url = 'https://youtu.be/MareArts' # Add your video url here
main(video_url)

..


Thank you.

www.marearts.com

πŸ™‡πŸ»‍♂️

No comments:

Post a Comment