A simple guide to download videos from YouTube using python
- Download YouTube Videos
- Saving as subclip (saving a portion of the video)
- Converting to MP3
- Required Tools:
- pip install pytube and moviepy
from pytube import YouTube from moviepy.editor import * # download a file from youtube youtube_link = 'https://www.youtube.com/watch?v=yourtubevideos' w = YouTube(youtube_link).streams.first() w.download(output_path="/your/target/directory") # download a file with only audio, to save space # if the final goal is to convert to mp3 youtube_link = 'https://www.youtube.com/watch?v=targetyoutubevideos' y = YouTube(youtube_link) t = y.streams.filter(only_audio=True).all() t.download(output_path="/your/target/directory")
Downloading videos from a YouTube playlist
import requests import re from bs4 import BeautifulSoup website = 'https://www.youtube.com/playlist?list=yourfavouriteplaylist' r= requests.get(website) soup = BeautifulSoup(r.text) tgt_list = [a['href'] for a in soup.find_all('a', href=True)] tgt_list = [n for n in tgt_list if re.search('watch',n)] unique_list=  for n in tgt_list: if n not in unique_list: unique_list.append(n) # all the videos link in a playlist unique_list = ['https://www.youtube.com' + n for n in unique_list] for link in unique_list: print(link) y = YouTube(link) t = y.streams.all() t.download(output_path="/your/target/directory")
Converting from MP4 to MP3 (from a folder with mp4 files)
import moviepy.editor as mp import re tgt_folder = "/folder/contains/your/mp4" for file in [n for n in os.listdir(tgt_folder) if re.search('mp4',n)]: full_path = os.path.join(tgt_folder, file) output_path = os.path.join(tgt_folder, os.path.splitext(file) + '.mp3') clip = mp.AudioFileClip(full_path).subclip(10,) # disable if do not want any clipping clip.write_audiofile(output_path)
Does not work error Http 403 forbidden
Hi Mario, thanks for highlighting. Yes, currently pytube is broken. You can refer to some of the hacks in the link: https://github.com/nficano/pytube/issues/399. You can try some of the approaches while waiting for the final fix. Thanks.
Has anyone tried YouTube 321? http://youtube321.com/
There is an error in the code IndentationError: expected an indented block
Hi Mune, are you able to email me your code and I take a look or may I know which part of the code did the indentation error occurs?