def download(self, playlist_url, num_urls=-1, resolution=None, proxies=None): ''' Scraper function for downloading videos from a youtube playlist Args: playlist_url: URL of vimeo video to be scraped num_urls: Maximum number of URLs to be fetched from the playlist resolution: Output video resolution. If unspecified then highest quality available is chosen proxies: dict, A dictionary containing proxy information ''' if proxies is None: print("WARNING: No proxies received. " "All videos might not get downloaded because of HTTP Error 429 (Too Many Requests)") playlist = pytube.Playlist(playlist_url, proxies) video_urls = playlist.video_urls for url in video_urls[:num_urls]: yt = pytube.YouTube(url) print("-" * 75) print("File Details: ") print("Title: ", yt.title, "\nAuthor: ", yt.author, "\nLength: ", yt.length) print("-" * 75) if resolution: yt.streams.get_by_resolution(resolution).download(self.out_path) else: yt.streams.get_highest_resolution().download(self.out_path) print(f"Finished downloading {yt.title}")
def main(): global play_again # play again is defined globally, and to access it we need to say global play_again while play_again: # while play_again is true, we should keep running the program again and again play_again = False # make it False so the loop doesn't run unless the user specifically makes it True window.intro_win() # gets the URL and assigns it to the global vairable URL also checks if the type of the url is a single video, # or a playlist and then assigns that to the global variable TYPE if TYPE == 'SINGLE': # if the video is a single video, then do these things # youtube object used to getting info that is common to both single and playlist downlaods yt = pt.YouTube(URL) # this creates an object of the Youtube Class, that has all the information about our playlist. window.sel_download_win_single(URL, yt) # now we can call this function to run and display all the things. else: # if the video is a playlist rather than a single video. playlist = pt.Playlist(URL) # this is a playlist object of the class Playlist. playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") # changes the regex of the youtube playlise object window.sel_downlaod_win_playlist(URL, playlist) # now we call this function to run display, download and do all the things. # as play_again is a global variable, the functions that we called will change the value of the variable if the user presses 'one more' # if the user does not press 'one more' then the value of play again remains false, as we assigned the value to be false previously. if not play_again: # in which case, say thank you and exit the while loop, thereby exiting the program. print('Thanks for using Kappa video downloader')
def connect_youtube_playlist(url): stream_itags = {"360p": "18", "480p": "135", "720p": "22"} playlist = pytube.Playlist(url) # get the video codec = None while codec not in stream_itags: print(f"360p downloads 360 pixels - Press Enter for Default(720p)") codec = str(input("Enter the type of codec for download: ")) if codec == "": codec = stream_itags["720p"] #download playlists start_count = 1 print(f"Number of videos in playlist is {len(playlist)}") while start_count >= len(playlist): print(f"Press Enter to start from the begining!") start_count = int( input("What position of the playlist do you want to start from? ")) start_count -= 1 for _, url in enumerate(playlist): if _ < start_count: continue video = pytube.YouTube(url) stream = video.streams.get_by_itag(stream_itags[codec]) print(f"Downloading video {_ + 1}...") stream.download() print(f"Completed donwload of video {_ + 1}")
def download_playlist(playlist_url, playlist_path): """ This is the function to download a playlist :param playlist_url: URL of the playlist :param playlist_path: Download directory :return: None """ playlist = pytube.Playlist(playlist_url) video_link = pytube.YouTube(playlist[0]) video = video_link.streams.filter(progressive=True) video_quality(video) user_quality = final_value for each_video in playlist: each_video_link = pytube.YouTube(each_video) reduced_video = each_video_link.streams.filter(progressive=True) # We use this exception if there are no such value in video we get the best first stream try: reduced_video[user_quality].download( playlist_path.replace("\\", "\\\\")) except: reduced_video.first().download(playlist_path.replace("\\", "\\\\")) message("The Download Is Complete.", "Success", "img//success.ico")
def download_playlist(playlist_url): """Wrapper for downloading the entire or parts of a public youtube playlist. Also supports the --mp3 option. :param str playlist_url: Quoted or unquoted youtube playlist URL """ try: pytube_playlist = pytube.Playlist(playlist_url) if not pytube_playlist: raise ValueError() # Suppress output of pytube playlist generator with contextlib.redirect_stdout(None): playlist_size = sum(1 for _ in pytube_playlist.video_urls) if playlist_size > 0: for video_url in pytube_playlist.video_urls: if MP3_ONLY: download_audio(video_url, playlist=helpers.safe_filename( pytube_playlist.title)) else: download_video(video_url, playlist=helpers.safe_filename( pytube_playlist.title)) else: logger.warning(f"No videos detected in '{pytube_playlist.title}'") except pytube.exceptions.RegexMatchError: logger.error(f'Playlist-URL: "{playlist_url}" is invalid!') except ValueError: logger.error(f'Playlist-URL: "{playlist_url}" is not accessible!')
def download(link: str, playlist: bool, format: str): if playlist == False and format == "mp3": return download_convert_video(link) elif playlist == False and format == "mp4": return download_video(link) elif playlist == True and format == "mp4": pl = pytube.Playlist(link) pl._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") return download_playlist(pl.video_urls) elif playlist == True and format == "mp3": pl = pytube.Playlist(link) pl._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") return download_convert_playlist(pl.video_urls) else: print("error with video parameters to download") exit()
def playlist(): pl = pytube.Playlist(url) looping = 0 while looping < 1: mode = input(""" Silahkan pilih Resolusi : 1. Lowest Resolution 2. Highest Resolution 3. Audio Only """) print("Downloading ....") if mode == "1": for videos in pl.videos: videos.streams.get_lowest_resolution().download('./Download') print(videos.title, " --- has been downloaded --- ") looping += 1 elif mode == "2": for videos in pl.videos: videos.streams.get_highest_resolution().download('./Download') print(videos.title, " --- has been downloaded --- ") looping += 1 elif mode == "3": for videos in pl.videos: videos.streams.get_audio_only().download('./Download') print(videos.title, " --- has been downloaded --- ") looping += 1 else: print("\nResolusi yang Anda pilih salah!!!")
def check_url(self): text = self.url_line_edit.text() is_v = self.is_v(text) is_p = self.is_p(text) if not is_v and not is_p: self.url_line_edit.setText("Please enter a valid url") return self.folder_line_edit.setHidden(False) self.select_folder_push_button.setHidden(False) self.quality_combo_box.setHidden(False) self.start_push_button.setHidden(False) video = pt.YouTube(text) if is_v else pt.YouTube( pt.Playlist(text).video_urls[0]) self.quality_combo_box.clear() self.quality_combo_box.addItem(SELECT_QUALITY_PROMPT_STRING) options = [] for stream in video.streams: vora, ext = stream.mime_type.split("/") if vora == "video": options.append( f"{ext.upper()} file at {stream.resolution} resolution") else: options.append(f"MP3 file at {stream.abr} bitrate" ) if ext.upper() == "WEBM" else None self.quality_combo_box.addItems(sorted(list(set(options))))
def __init__(self,PlaylistUrl,downloadProgress3,downloadComplete3): self.playlist = pytube.Playlist(PlaylistUrl) self.video_streams=None self.urls = self.playlist.video_urls self.video = None self.resolutions=['720p','360p'] self.downloadProgress3 = downloadProgress3 self.downloadComplete3 = downloadComplete3 self.k = 0 self.video_count = len(self.urls) self.digits = len(str(len(self.urls))) self.playlist_title = self.playlist.title() try: with open(output_cfg_file, 'r') as f: path = f.read().strip() if sys.platform == 'win32': self.output_path = path + '\\' else: self.output_path = path + '/' # TEST THIS FOR LINUX except: traceback.print_exc() self.n = 0 self.time1 = None self.time2 = None self.old_remaining = 0 self.download_speed = 0 self.download_percent = 0 self.filesize = 1 self.video_titles = (self.videoTitleFinder(link) for link in self.urls)
def parse_url(self, url): """ Parses URL and finds out which method to use. TODO: Do this properly. :param url: Video URL. """ if "youtube.com" not in url: raise ValueError("'url' must be a valid youtube url") elif 'list' in url: playlist = pytube.Playlist(url) playlist.playlist_url = playlist.construct_playlist_url() playlist.populate_video_urls() for u in playlist.video_urls: u = u.replace("https", "http") u = u.replace("www.", "") self.video_urls.append(u) elif 'watch?' in url: self.video_urls.append(url) elif 'channel' in url or 'user' in url: if 'channel' in url: channel_id = url.split("channel/")[1] self.video_urls = self.api.get_videos_in_channel(channel_id) elif 'user' in url: channel_id = self.api.get_channel_id_from_user( url.split("user/")[1]) self.video_urls = self.api.get_videos_in_channel(channel_id) else: raise ValueError("Unrecognized youtube url")
def main(): global again, playlist_URLS while again: again = False window.intro_win() # gets the URL if TYPE == 'SINGLE': # youtube object used to getting info that is common to both single and playlist downlaods yt = pt.YouTube(URL) fio.write.add_to_data_csv(yt, URL) window.sel_download_win_single(URL, yt) elif TYPE == 'PLAYLIST': playlist = pt.Playlist(URL) playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") playlist_URLS = playlist.video_urls print(playlist_URLS[0]) T1 = threading.Thread(target=generate_vids) T1.start() app = loading() T2 = threading.Thread(target=app.mainloop()) T2.start() window.sel_downlaod_win_playlist(playlist) elif TYPE == 'STATISTICS': window.statistics() if not again: print('Thanks for using Kappa video downloader')
def playListDownload(self): try: self.playList = self.playListLink.text() youtube_playlist = pytube.Playlist(self.playList) self.lengList = str(len(youtube_playlist)) self.downloadList = 0 for playlist in youtube_playlist: self.playListDownloadAlert.setText( str(self.downloadList) + "/" + self.lengList + " Done") video = pytube.YouTube( playlist, on_progress_callback=self.on_progressPlayList) stream = video.streams.get_highest_resolution() self.filesize = stream.filesize stream.download(self.playListDir + "/") self.downloadList += 1 self.playListDownloadAlert.setText( str(self.downloadList) + "/" + self.lengList + " Done") self.downloadList = 0 except: if self.videoLink.text() == "": self.errorMessage = QMessageBox.warning( self, "Error", "Please Write A Playlist Url") else: self.errorMessage = QMessageBox.warning( self, "Error", "Playlist Not Found")
def searchPlaylist(self): try: self.search = self.playListLink.text() self.playListInfo = pytube.Playlist(self.search) self.playlistTitle = self.playListInfo.title self.playListInfoText.setText("Playlist Title: " + self.playlistTitle) self.fileSize = 0 self.videoSize = 0 for playlist in self.playListInfo: video = pytube.YouTube(playlist) video = video.streams.get_highest_resolution() self.filesize += video.filesize self.videoSize += 1 self.playListInfoText.setText( "PlayList Title: " + self.playlistTitle + "\nFile Size: " + str(round((self.filesize / 1048576), 2)) + " MB\n" + str(self.videoSize) + " Video") except: if self.videoLink.text() == "": self.errorMessage = QMessageBox.warning( self, "Error", "Please Write A Playlist Url") else: self.errorMessage = QMessageBox.warning( self, "Error", "Playlist Not Found!")
async def handler(event): async with bot.conversation(event.chat, timeout=None) as conv: await conv.send_message( 'Hi I will download any youtube audio file you wish in mp3 format') while True: await conv.send_message('Please choose one of the buttons', buttons=[ Button.text('Download a song', resize=True), Button.text('Download a playlist') ]) ans = await conv.get_response() if ans.text == 'Download a song': try: await conv.send_message( 'Please send me a youtube link to the song') link = await conv.get_response() await conv.send_message( 'Downloading... this may take some time') link = link.text title = Download(str(link)) await conv.send_file(title + '.mp3') os.remove(title + '.mp3') os.remove('song.mp4') except Exception as e: print(e) await conv.send_message( "error... please make sure you insert a correct url") elif ans.text == "Download a playlist": try: await conv.send_message( 'Please send me a youtube link to the playlist') link = await conv.get_response() await conv.send_message( 'Downloading... this may take some time') link = link.text pl = pytube.Playlist(link) pl.download_all('playlists/') for song in os.listdir('playlists/'): old_file = os.path.join('playlists', song) new_file = os.path.join('playlists', song[1:]) os.rename(old_file, new_file) for song in os.listdir('playlists/'): print(song) video = VideoFileClip('playlists/' + song) video.audio.write_audiofile('playlists/' + song.replace(".mp4", "") + '.mp3') await conv.send_file('playlists/' + song.replace(".mp4", "") + '.mp3') os.remove('playlists/' + song.replace(".mp4", "") + '.mp3') os.remove('playlists/' + song) except Exception as e: print(e) await conv.send_message( "error... please make sure you insert a correct url")
def _populate_playlist_urls(url): """ populating [ ] with youtube individual links :param url: provide url for request to be made for list of links :return: list """ res = pytube.Playlist(url) res.populate_video_urls() return res.video_urls
def download_playlist(link_playlist=str): try: playlist = pytube.Playlist(link_playlist) print(f"Existem {len(playlist.video_urls)} videos na Playlist!") playlist.download_all(caminho + "/playlist") except: return "Erro ao fazer Download da Playlist" else: return "Download Exceutado com Sucesso!"
def Playlist(): url = U.get() playlist = pytube.Playlist(url) for url in playlist: video = pytube.YouTube(url) stream = video.streams.get_by_itag(18) messagebox.showinfo("Playlist", "Downloading...") stream.download() messagebox.showinfo("Playlist", "Done!")
def download_youtube_mp4_playlist(sender, data): with window("File downloader"): general_url = get_value("URL") playlist = pytube.Playlist(general_url) if general_url == "": log_warning(logger="logger_general", message="URL is empty") else: for url in playlist: pytube.YouTube(url).streams.first().download('./videos')
def playlist_func(url, directory): try: playlist = pytube.Playlist(url) file_object = open(directory + "/links.log", "a") file_object.write('Playlist Url :' + url + '\n') file_object.close() print('There are {0}'.format(len(playlist.video_urls))) for url in playlist.video_urls: single_url(url, directory) except: single_url(url, directory)
def Playlist(downlink): SaveFile("YTPlaylist") try: yt = pytube.Playlist(downlink) for videos in yt.videos: try: videos.streams.filter(progressive=True, file_extension='mp4').last().download() except Exception as down: messagebox.showerror("error", "Can't connect to Net") messagebox._show("Done", "Playlist is downloaded") except Exception as link: messagebox.showerror("error", 'Enter a correct Link')
def dw_playlist(): opcion = tks.askstring( "Opción...", "Descargar vídeo y audio: 1. Descargar solo audio: 2.") while opcion != "1" and opcion != "2": opcion = tks.askstring( "Opción...", "Opción no válida. Descargar vídeos: 1. Descargar solo audio: 2.") url = tks.askstring("URL", "Pon la url") playlist = pytube.Playlist(url) for url in playlist: video = pytube.YouTube(url) raw_name = video.title descarga(url, raw_name, opcion)
def get_remote_songs(self): query = Config.session.query(UserSetting) users: List[UserSetting] = query.all() result = [] for row in users: if (row.youtube_url is not None) or (row.youtube_url != ""): playlist = pytube.Playlist(row.youtube_url) # playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") for url in playlist.video_urls: result.append((row.chat_id, str(url))) return result
def download_playlist(self, playlist_url, playlist_slice=None): # Downloads a Playlist playlist = pytube.Playlist(playlist_url) playlist.populate_video_urls() urls = playlist.video_urls if playlist_slice is not None: urls = urls[playlist_slice[0] - 1:playlist_slice[1]] self.download_from_urls(urls)
def playlist_scraper(url, output_directory): playlist = pytube.Playlist(url) playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") for video_url in playlist: video = pytube.YouTube(video_url) print("Downloading {0}".format(video.title)) streams = video.streams.filter(file_extension="mp4", progressive=True) max_res = max([stream.resolution for stream in streams]) stream = streams.filter(resolution=max_res)[0] stream.download(output_directory) print("Download Complete")
def channel_links(channel_url): if not os.path.exists('./subs'): os.mkdir('./subs') pl = pytube.Playlist(channel_url) lk = pl.parse_links() name = re.search('.*/user/(.+)/', channel_url) with open(f'./subs/channel_links_{name.group(1)}.txt', 'w') as f: f.writelines('\n'.join(lk)) return lk
def down_play_list_youtube(url): play_list = pytube.Playlist(url) if not os.path.exists('play_list'): os.makedirs('play_list') os.chdir(str(pathlib.Path(__file__).parent.absolute()) + "/play_list") for x, url in enumerate(play_list): # pytube.YouTube(url).streams.get_by_itag(22).download() video = pytube.YouTube(url) stream = video.streams.get_by_itag(22) logging.debug(f'start download video : {x}') stream.download()
def playlist(): print("Enter the Playlist url :") url = input("") playlist = pytube.Playlist(url) for url in playlist: video = pytube.YouTube(url) stream = video.streams.get_by_itag(22) try: stream.download(output_path=path()) except: print( "sry it's not working for a video, trying for the next video..." ) pass return print("It's gud dude, your Playlist have been downloaded!")
def download_playlist(link, quality, destination_path): ''' Downloads the playlist from the youtube. :param link: URL of the youtube playlist. :param quality: Quality/Resolution of the video :param destination_path: Path of where to store downloaded videos. ''' playlist_object = pytube.Playlist(link) os.mkdir(os.path.join(destination_path, playlist_object.title)) downloaded_video_location = os.path.join( destination_path, playlist_object.title) print(f'[+] Downloading playlist - {playlist_object.title}') download_videos(playlist_object.video_urls, quality, downloaded_video_location) print(f'[+] Completed Downloading playlist - {playlist_object.title}')
def playlist_downloader(body): playlist = pytube.Playlist(body['url']) folder_name = playlist_id_maker(playlist) upper_limit = int(body['ul']) lower_limit = int(body['ll']) - 1 resolution = body['resolution'] for url in playlist.video_urls[lower_limit:upper_limit]: youtube = pytube.YouTube(url) failSafeDownload(youtube, resolution, folder_name) zipfile_name = file_zipper(folder_name) deleteFolder(folder_name) return constructMediaLink(zipfile_name)
def job(): pl = pytube.Playlist( "https://www.youtube.com/watch?v=xottL3JnaQw&list=PLKjihOYfsIYuD-Z5LvtrzLb68EkOcAxz7" ) pl.download_all(os.path.join("./", "source")) print("download video completed") threads = [] file_list = os.listdir("./source") file_list.sort() # print(file_list[1]) for file in file_list: thread = Thread(target=Video2Raw, args=(file, )) threads.append(thread) thread.start() for thread in threads: thread.join()