I'm trying to download my video playlist and convert it to mp3 extension using pytube,moviepy,re. Everything works but when it hits a number it stops working.
How can I fix this?
from pytube import YouTube
from pytube import Playlist
import os
import moviepy.editor as mp #to convert the mp4 to wav then mp3
import re
playlist = Playlist("https://www.youtube.com/playlist?list=PLb2p41g_hNVOeBy3OjGTdXKgscedya9f_")
for url in playlist:
print(url)
for vid in playlist.videos:
print(vid)
for url in playlist:
YouTube(url).streams.filter(only_audio=True).first().download("./Downloads/Music_2")
folder = "./Downloads/Music_2"
for file in os.listdir(folder):
if re.search('mp4', file):
print("Converting: " + file)
mp4_path = os.path.join(folder,file)
mp3_path = os.path.join(folder,os.path.splitext(file)[0]+'.mp3')
new_file = mp.AudioFileClip(mp4_path)
new_file.write_audiofile(mp3_path)
os.removed(mp4_path)
Error Code;
Traceback (most recent call last):
File "C:\Users\user\Downloads\Projects\Python\main.py", line 14, in <module>
YouTube(url).streams.filter(only_audio=True).first().download("./Downloads/Music_3")
^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 296, in streams
return StreamQuery(self.fmt_streams)
^^^^^^^^^^^^^^^^
File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 176, in fmt_streams
stream_manifest = extract.apply_descrambler(self.streaming_data)
^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\Downloads\Projects\Python\venv\Lib\site-packages\pytube\__main__.py", line 161, in streaming_data
return self.vid_info['streamingData']
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
KeyError: 'streamingData'
Process finished with exit code 1
I was able to reproduce your issue with the latest pytube version.
More precisely these video ids failed to be downloaded on first trial. However after another trial only the following video ids are still not available for download: bFfSn7RKgwE, pYEwoUgKhV8 and UtF6Jej8yb4. pYEwoUgKhV8 is a members-only video so you are obliged to pay to access it and bFfSn7RKgwE and UtF6Jej8yb4 are just age-restricted, you can access these videos with yt-dlp for instance.
So there is no pytube issue here.
from pytube import YouTube
from moviepy.editor import *
with open('test.txt') as f:
lines = f.readlines()
for x in lines:
yt = YouTube(x)
yt.streams.filter(file_extension='mp4').first().download()
mp4_file = f"{yt.title}.mp4"
mp3_file = f"{yt.title}.mp4"
videoclip = VideoFileClip(mp4_file)
audioclip = videoclip.audio
audioclip.write_audiofile(mp3_file)
audioclip.close()
videoclip.close()
title = f"{yt.author} {yt.title}"
print(title)
Trying to convert downloaded mp4 from Youtube videos to mp3 using pytube and moviepy. Downloading the mp4's works fine however I run into this error when the conversion part happens: https://i.imgur.com/JhJMQgR.png
Tried updating ffmpeg, but it didn't help.
I'm trying to do a program that downloads the videos of a playlist from youtube, this is the program:
from pytube import Playlist
from pytube import YouTube
playlist = Playlist('https://www.youtube.com/playlist?list=PLZ1u221jNfYGCxHU4RbChwG60X-_nq8HK')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
for video_url in playlist.video_urls:
f = open (r'D:\Nueva carpeta (4)\lista_viejas.txt','a')
f.write("\n")
f.write(str(video_url))
f.close()
with open(r'D:\Nueva carpeta (4)\lista_viejas.txt', 'r') as file1:
with open(r'D:\Nueva carpeta (4)\lista_viejass.txt', 'r') as file2:
with open (r'D:\Nueva carpeta (4)\output.txt', "w") as out_file:
f2_lines = set(file2)
for line in file1:
if line not in f2_lines:
yt = YouTube(str(line))
video = yt.streams.first()
video.download(r'D:\Nueva carpeta (4)')
out_file.write(line)
f2_lines.add(line)
I dont know why I get this error in this part:
Exception has occurred: RegexMatchError
regex_search: could not find match for (?:v=|\/)([0-9A-Za-z_-]{11}).*
File "C:\Users\Andres\Desktop\Untitled-1.py", line 22, in <module>
yt = YouTube(str(line))
yt = YouTube(str(line))
video = yt.streams.first()
video.download(r'D:\Nueva carpeta (4)')
If I change the parameter "line" to line_prove=input(), it works.
ok i dont know why, but i tried to writte it in another way, and its fix it i just added
YouTube(line).streams.first().download(r'D:\Nueva carpeta (4)'
I'm trying to relearn python after a long break and I can not manage to get this piece of code to work, no matter what I do.
It just keeps telling me
File "/Users/fletch/PycharmProjects/untitled1/YT Download.py", line 18, in <module>
mp4files = yt.filter('mp4')
NameError: name 'yt' is not defined
The entire program looks like this
from pip._vendor.distlib.compat import raw_input
import pytube
# save path
from pytube import YouTube
SAVE_PATH = "/Users/fletch/Movies"
# Get Video URL from User
url = raw_input("Please input the link of the Video you want to download: \n".rstrip())
try:
yt = YouTube(url)
except:
print("Connection Error")
# Filters Out MP4 Files
mp4files = yt.filter('mp4')
# Set File Name
filename = raw_input("Please name your file: \n".rstrip())
yt.set_filename(filename)
# Get the Video
d_video = yt.get(mp4files[-1].extension, mp4files[-1].resolution)
try:
d_video.download(SAVE_PATH)
except:
print("Unknown Error, Try Again Later")
print("Task Complete")
Any help will be greatly appreciated
I am looking to download a YouTube playlist using the PyTube library. Currently, I am able to download a single video at a time. I cannot download more than one video at once.
Currently, my implimentation is
import pytube
link = input('Please enter a url link\n')
yt = pytube.YouTube(link)
stream = yt.streams.first()
finished = stream.download()
print('Download is complete')
This results in the following output
>> Download is complete
And the YouTube file is downloaded. When I try this with a playlist link (An example) only the first video is downloaded. There is no error outputted.
I would like to be able to download an entire playlist without re-prompting the user.
You can import Playlist to achieve this. There is no reference to Playlist in the redoc, though there is a section in the GitHub repo found here. The source of the script is in the repo here.
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/watch?v=58PpYacL-VQ&list=UUd6MoB9NC6uYN2grvUNT-Zg')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
playlist.download_all()
NOTE: I've found the supporting method Playlist.video_urls does not work. The videos are still downloaded however, as evidenced here
The solutions above no longer work. Here's a code which downloads the sound stream of the videos referenced in a Youtube playlist. Pytube3 is used, not pytube. Note that the playlist must be public for the download to succeed. Also, if you want to download the full video instead of the sound track only, you have to modify the value of the Youtube tag constant. The empty Playlist.videos list fix was taken from this Stackoverflow post:PyTube3 Playlist returns empty list
import re
from pytube import Playlist
YOUTUBE_STREAM_AUDIO = '140' # modify the value to download a different stream
DOWNLOAD_DIR = 'D:\\Users\\Jean-Pierre\\Downloads'
playlist = Playlist('https://www.youtube.com/playlist?list=PLzwWSJNcZTMSW-v1x6MhHFKkwrGaEgQ-L')
# this fixes the empty playlist.videos list
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(playlist.video_urls))
for url in playlist.video_urls:
print(url)
# physically downloading the audio track
for video in playlist.videos:
audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO)
audioStream.download(output_path=DOWNLOAD_DIR)
if one needs to download the highest quality video of each item in a playlist
playlist = Playlist('https://www.youtube.com/watch?v=VZclsCzhzt4&list=PLk-w4cD8sJ6N6ffzp5A4PQaD76RvdpHLP')
for video in playlist.videos:
print('downloading : {} with url : {}'.format(video.title, video.watch_url))
video.streams.\
filter(type='video', progressive=True, file_extension='mp4').\
order_by('resolution').\
desc().\
first().\
download(cur_dir)
this code allows you to download a playlist to your assigned folder
import re
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=Pd5k1hvD2apA0DwI3XMiSDqp')
DOWNLOAD_DIR = 'D:\Video'
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(playlist.video_urls))
for url in playlist.video_urls:
print(url)
for video in playlist.videos:
print('downloading : {} with url : {}'.format(video.title, video.watch_url))
video.streams.\
filter(type='video', progressive=True, file_extension='mp4').\
order_by('resolution').\
desc().\
first().\
download(DOWNLOAD_DIR)
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=PL6gx4Cwl9DGCkg2uj3PxUWhMDuTw3VKjM')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
for video_url in playlist.video_urls:
print(video_url)
playlist.download_all()
https://www.youtube.com/watch?v=HjuHHI60s44
https://www.youtube.com/watch?v=Z40N7b9NHTE
https://www.youtube.com/watch?v=FvziRqkLrEU
https://www.youtube.com/watch?v=XN2-87haa8k
https://www.youtube.com/watch?v=VgI4UKyL0Lc
https://www.youtube.com/watch?v=BvPIgm2SMG8
https://www.youtube.com/watch?v=DpdmUmglPBA
https://www.youtube.com/watch?v=BmVmJi5dR9c
https://www.youtube.com/watch?v=pYNuKXjcriM
https://www.youtube.com/watch?v=EWONqLqSxYc
https://www.youtube.com/watch?v=EKmLXiA4zaQ
https://www.youtube.com/watch?v=-DHCm9AlXvo
https://www.youtube.com/watch?v=7cRaGaIZQlo
https://www.youtube.com/watch?v=ZkcEB96iMFk
https://www.youtube.com/watch?v=5Fcf-8LPvws
https://www.youtube.com/watch?v=xWLgdSgsBFo
https://www.youtube.com/watch?v=QcKYFEgfV-I
https://www.youtube.com/watch?v=BtSQIxDPnLc
https://www.youtube.com/watch?v=O5kh_-6e4kk
https://www.youtube.com/watch?v=RuWVDz-48-o
https://www.youtube.com/watch?v=-yjc5Y7Wbmw
https://www.youtube.com/watch?v=C5T59WsrNCU
https://www.youtube.com/watch?v=MWldNGdX9zE
I'm using pytube3 9.6.4, not pytube.
Now Playlist.video_urls works well.
And Playlist.populate_video_urls() function was deprecated.
from pytube import YouTube
from pytube import Playlist
SAVE_PATH = "E:/YouTube" #to_do
#link of the video to be downloaded
links= "https://youtube.com/playlist?list=PLblh5JKOoLUL3IJ4- yor0HzkqDQ3JmJkc"
playlist = Playlist(links)
PlayListLinks = playlist.video_urls
N = len(PlayListLinks)
#print('Number of videos in playlist: %s' % len(PlayListLinks))
print(f"This link found to be a Playlist Link with number of videos equal to {N} ")
print(f"\n Lets Download all {N} videos")
for i,link in enumerate(PlayListLinks):
yt = YouTube(link)
d_video = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()
d_video.download(SAVE_PATH)
print(i+1, ' Video is Downloaded.')
You can check this repository to download playlists and individual videos and keep them in different directories.
https://github.com/pushpendra050/Pytube-for-Playlist-download
this work for me in windows 11 or 10.5
Original code: Jean-Pierre Schnyder
import re
from pytube import Playlist
DOWNLOAD_DIR = input ("Download dir")
playlist = input ("Link:")
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(playlist.video_urls))
for url in playlist.video_urls:
print(url)
for video in playlist.videos:
audioStream = video.streams.get_highest_resolution()
audioStream.download(output_path=DOWNLOAD_DIR)
Though it seems like a solved problem, but here is one of my solutions which may help you to download the playlist specifically as video of 1080P 30 FPS or 720P 30 FPS (if 1080P not available).
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=PLeo1K3hjS3uvCeTYTeyfe0-rN5r8zn9rw')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
# Loop through all videos in the playlist and download them
for video in playlist.videos:
try:
print(video.streams.filter(file_extension='mp4'))
stream = video.streams.get_by_itag(137) # 137 = 1080P30
stream.download()
except AttributeError:
stream = video.streams.get_by_itag(22) # 22, 136 = 720P30; if 22 still don't work, try 136
stream.download()
except:
print("Something went wrong.")
This works for me. Just takes the URLs in the playlist and downloads them one by one:
from pytube import Playlist
playlist = Playlist('URL')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
for video_url in playlist.video_urls:
print(video_url)
urls.append(video_url)
for url in urls:
my_video = YouTube(url)
print("*****************DOWNLOAD VID*************")
print(my_video.title)
my_video = my_video.streams.get_highest_resolution()
path = "PATH"
my_video.download(path)
print("VIDEO DOWNLOAD DONNNNE")
import pytube
from pytube import Playlist
playlist = Playlist('plylist link')
num = 0
for v in playlist.videos:
print(v.watch_url)
one = pytube.YouTube(v.watch_url)
one_v = one.streams.get_highest_resolution()
name = f"{0}" + one_v.default_filename
one_v.download()
num = num + 1
Download all playlist
This works flawlessly to download complete playlist
check pytube github to install
pip install pytube
Now, go to this folder and open cipher.py
D:\ProgramData\Anaconda3\Lib\site-packages\pytube\
replace at line 273
function_patterns = [
r'a\.[a-zA-Z]\s*&&\s*\([a-z]\s*=\s*a\.get\("n"\)\)\s*&&\s*.*\|\|\s*(.*)\(',
r'\([a-z]\s*=\s*([a-zA-Z0-9$]{3})(\[\d+\])?\([a-z]\)',
]
main.py
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/playlist?list=PLwdnzlV3ogoXUifhvYB65lLJCZ74o_fAk')
playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(playlist.video_urls))
for url in playlist.video_urls:
print(url)
for video in playlist.videos:
video.streams.get_highest_resolution().download()
this may not work, the code below works for every case
from pytube import Playlist
from pytube import YouTube
from pytube import Playlist
playlist = Playlist('https://www.youtube.com/watch?v=UPFKAG9rYOE&list=PLknwEmKsW8OtK_n48UOuYGxJPbSFrICxm')
print('Number of videos in playlist: %s' % len(playlist.video_urls))
for video_url in playlist.video_urls:
print(video_url)
video=YouTube(video_url)
try:
#video.streams.first().download()
video.streams.filter(res="720p").first().download()
except:
continue