def list(url, mName=""): pl = Playlist(url) index = 0 p = progressbar.ProgressBar() p.start() f = open('list_' + mName + '.csv', 'w') f.close() for i in pl.parse_links(): index = index + 1 # print(i.replace("/watch?v=","")) stYoutube = subtitleYoutube(i.replace("/watch?v=", ""), mName) stYoutube.downloadSubAndWav() stYoutube.cutSubtitle() p.update(int(index / len(pl.parse_links()) * 100)) p.finish()
def from_playlist_url(url): pli = Playlist(url) pli.parse_links() pli.populate_video_urls() output = dict() output['type'] = 'playlist' output['title'] = pli.title() url = pli.construct_playlist_url() output['url'] = url output['playlist_id'] = _get_playlist_id(url) video_urls = pli.parse_links() output['video_urls'] = video_urls output['video_ids'] = [v.split('=')[1] for v in video_urls] return output
def getAllLinks(playList): allLinks = [] youtubeLink = 'https://www.youtube.com' pl = Playlist(playList) for linkprefix in pl.parse_links(): allLinks.append(youtubeLink + linkprefix) return allLinks
def videos_download(url, qualty): print("->Starting Youtube video list downloading") no = 1 lnks = [] target_playlist = Playlist(url) for i in target_playlist.parse_links(): lnk = "https://www.youtube.com" + i yt = YouTube(lnk) print(str(no), ")", yt.title, lnk) lnks.append(lnk) no = no + 1 print("\n") for i in lnks: if qualty == '360': yt = YouTube(i) st = yt.streams.get_by_itag('43') try: st.download() print("[+]", yt.title, " was downloaded(360p)") except: print("[-]", yt.title, "couldnt downloaded(360p)") elif qualty == '720': yt = YouTube(i) st = yt.streams.get_by_itag('22') try: st.download() print("[+]", yt.title, " was downloaded(720p)") except: print("[-]", yt.title, "couldnt downloaded(720p)")
def download(): if (videotype.get() == 1): downloadYouTube(str(urlInput.get()), path.get()) urlInput_label = tk.Label(frame, text=YouTube(urlInput.get()).title + " downloaded !", bg="#041824", fg="#ffffff", font=("Courier", 10), wraplength=400) urlInput_label.place(y=370, relwidth=1, relheight=0.2) elif (videotype.get() == 2): pl = Playlist(urlInput.get()) pl.populate_video_urls() for link in pl.parse_links(): videolink = 'https://www.youtube.com' + link downloadYouTube(videolink, path.get()) urlInput_label = tk.Label(frame, text=YouTube(videolink).title + " downloaded !", bg="#041824", fg="#ffffff", font=("Courier", 10), wraplength=400) urlInput_label.place(y=370, relwidth=1, relheight=0.2)
def youtube_playlist_extract(playlist_url): # Create a list of all the individual urls in the Youtube playlist playlist = Playlist(playlist_url) urls_list = playlist.parse_links() for i in range(len(urls_list)): urls_list[i] = 'https://www.youtube.com' + urls_list[i] for link in urls_list: youtube_download(link)
def test_link_parse(): ob = Playlist(short_test_pl) expected = [ '/watch?v=m5q2GCsteQs', '/watch?v=5YK63cXyJ2Q', '/watch?v=Rzt4rUPFYD4', ] assert ob.parse_links() == expected
def parsing_youtube_list_page(self, video_list, author): pl = Playlist(video_list) # 下载用户视频列表 playlist_url = pl.parse_links() # 获取 playlist 中的视频网址 for v in playlist_url: video_url = "https://www.youtube.com" + v data = self.parsing_details_video(details_url=video_url, author=author) print(data) self.save_video(data=data)
def process(self, url, dir=DEFAULT_DIR): pl = Playlist(url, True) links = pl.parse_links() array = [] for link in links: url = ('https://www.youtube.com' + link + ", " + dir) array.append(url) return "\n".join(array)
def test_link_parse(): ob = Playlist( 'https://www.youtube.com/watch?v=m5q2GCsteQs&list=' 'PL525f8ds9RvsXDl44X6Wwh9t3fCzFNApw', ) expected = [ '/watch?v=m5q2GCsteQs', '/watch?v=5YK63cXyJ2Q', '/watch?v=Rzt4rUPFYD4', ] assert ob.parse_links() == expected
def get_urls_and_save(self): ''' parse the playlist with Playlist, and save the urls into redis ''' pl = Playlist(self.playlist_url) urls = pl.parse_links() for url in urls: url = 'https://www.youtube.com' + url print(url) if not self.redisClient.hash_get(self.playlist_url, url): self.redisClient.hash_set(self.playlist_url, url, 'False')
def main(): pl = Playlist( 'https://www.youtube.com/playlist?list=PL95lHvAv3fEkldbLqR0Ur9EX5JmmtrBfr' ) i = 0 for item in pl.parse_links(): print('youtube.com' + item) youtube = YouTube('youtube.com' + item) #print(youtube.title) #print(youtube.thumbnail_url) #a = Th(youtube) i += 1 print(i)
def echo(bot, update): print(update.message.text) if 'playlist' in update.message.text.lower(): from pytube import Playlist import threading import time pl = Playlist('https://www.youtube.com/playlist?list=PLQuDmj3ez49wUERdKxZYfoDVESQuvppH2') bot.send_message(chat_id=update.message.chat_id, text="São " + str(len(pl.parse_links())) + " videos \nEstou baixando :D") for link in pl.parse_links(): threading.Thread(target=download,args=(link,)).start() bot.send_message(chat_id=update.message.chat_id, text="Estou baixando o video \n" + getTitle(link)) time.sleep(5) elif 'https' in update.message.text: link = update.message.text title = getTitle(link) bot.send_message(chat_id=update.message.chat_id, text="Estou baixando seu video, " + title) music = download(link) bot.send_message(chat_id=update.message.chat_id, text="Seu video foi baixado, estou lhe enviando o seu audio") print("enviando") bot.send_audio(chat_id=update.message.chat_id, audio=open(music, 'rb'), title=title, timeout=999) print("enviado") elif int(update.message.text) < 5: print(int(update.message.text)) global id id = id.split('\n') id = id[int(update.message.text)] link = 'https://youtu.be/' + id title = getTitle(link) bot.send_message(chat_id=update.message.chat_id, text="Estou baixando seu video, " + title) music = download(link) bot.send_message(chat_id=update.message.chat_id, text="Seu video foi baixado, estou lhe enviando o seu audio") print("enviando") bot.send_audio(chat_id=update.message.chat_id, audio=open(music, 'rb'), title=title.encode(encoding='utf-8'), timeout=999) print("enviado") os.remove(music)
def download(): pl = Playlist("https://www.youtube.com/watch?v=m5vhIDNpigw&list=PL2UXTH6p_7LYvIwzfgKcC8js8ONiYlTlo") playlist_url = pl.parse_links() # 获取 playlist 中的视频网址 path = r'E:\folder' # 设置下载路径 failed = [] # 记录下载失败的视频 for i in tqdm(range(len(playlist_url))): URL = "https://www.youtube.com" + playlist_url[i] try: # 即使某个视频下载失败,还可以继续运行 yt = YouTube(URL) print("download ", yt.title) YouTube(URL).streams.first().download(path) except: print("failed ...") failed.append(i)
def DownloadList(self): AudioPlaylist = Playlist(self.Links) PlaylistLink = AudioPlaylist.parse_links() AudioLink = [] for item in PlaylistLink: AudioLink.append( (YouTube("https://www.youtube.com" + item).title ,"https://www.youtube.com" + item) ) print(AudioLink) if AudioLink: self.tableWidget.setRowCount(0) self.tableWidget.insertRow(0) for row , form in enumerate(AudioLink): for column , item in enumerate(form): self.tableWidget.setItem(row , column , QTableWidgetItem(item)) column += 1 self.tableWidget.insertRow(self.tableWidget.rowCount())
def main(): pl = Playlist( "https://www.youtube.com/playlist?list=PLRMCcJc0sUzswmhLqeea-jc182XZuJCjU" ) urls = pl.parse_links() print(urls) for url in urls: print("Now Download.....http://youtube.com{}".format(url)) try: yt = YouTube('http://youtube.com{}'.format(url)) (yt.streams.filter( progressive=True, file_extension='mp4').order_by( 'resolution').desc().first().download('./music')) except: print("pass") pass
class youtubeDowload(): def __init__(self): self.video = None self.url = 'your youtube link' self.pl = Playlist(self.url) # prepare playlist to download def downloadPlaylist(self): linkArray = self.getAllLinks() i = 0 for link in linkArray: try: print('start download ' + link) self.downloadVideo(link) print('complete download ' + link) i += 1 print('total= ' + str(len(linkArray)) + ', completed= ' + str(i) + ', remaining = ' + str(len(linkArray) - i)) except IndexError: print('can not download this link = ' + self.url) pass # get all youtube links from playlist to download one by one def getAllLinks(self): allLinks = [] youtubeLink = 'https://www.youtube.com' for linkprefix in self.pl.parse_links(): allLinks.append(youtubeLink + linkprefix) return allLinks # start download video def downloadVideo(self, link): self.yt = YouTube(link, on_progress_callback=self.show_progress_bar) self.video = self.yt.streams.filter( progressive=True, file_extension='mp4').order_by('resolution').desc().first() self.video.download() # to show percentage when download def show_progress_bar(self, stream, chunk, file_handle, bytes_remaining): size = self.video.filesize progress = (float(abs(bytes_remaining - size) / size)) * float(100) print('downloading ' + str(progress) + '%') return
def save_playlist_links(playlist_urls, links_dir): main_link = "https://www.youtube.com" links = [] for playlist_url in playlist_urls: pl = Playlist(playlist_url) for tmp_link in pl.parse_links(): link = main_link + tmp_link try: # 비공개영상 접근 불가, key error yt = YouTube(link) links.append(link) count += 1 print('Link read', count) except: print('Except') df = pd.DataFrame({'links': links}) df.to_csv(links_dir, index=False) print('Links saved !')
def download(self): print(self.get_quality()) playlist_url = self.link.text if playlist_url: pl = Playlist(playlist_url) folder_name = self.safe_filename(pl.title()) video_list = pl.parse_links() self.playlistLen = len(video_list) self.folder_path = 'D:/download/' + folder_name self.create_new_folder(self.folder_path) counter = 1 for x in video_list: self.total_size = 1 try: yt = YouTube("https://www.youtube.com/" + x) y_title = self.safe_filename(yt.title) yt.register_on_progress_callback(self.show_progress_bar) video_name = self.get_cnt(counter) + y_title video_path = video_name+"_v" audio_path = video_name+"_a" yt.streams.filter(adaptive=True, only_audio=True).first().download(self.folder_path, filename=audio_path) yt.streams.filter(adaptive=True).first().download(self.folder_path, filename=video_path) sss = [stream.subtype for stream in yt.streams.filter(adaptive=True).all()] file_extension_video = sss[0] sss = [stream.subtype for stream in yt.streams.filter(adaptive=True, only_audio=True).all()] file_extension_audio = sss[0] MergeVA.merge_va(isinstance, f"{self.folder_path}/{video_path}.{file_extension_video}", f"{self.folder_path}/{audio_path}.{file_extension_audio}", f"{self.folder_path}/{video_name}.mkv") os.remove(f"{self.folder_path}/{video_path}.{file_extension_video}") os.remove(f"{self.folder_path}/{audio_path}.{file_extension_audio}") caption = yt.captions.get_by_language_code('en') if caption: my_file = open(self.folder_path + '/' + self.get_cnt(counter) + y_title + ".srt", "w+", encoding='UTF8') my_file.writelines(caption.generate_srt_captions()) my_file.close() else: print("No Sub Found") except Exception as e: print("Can't Download: " + str(e)) counter += 1
def test_parse_links(request_get, playlist_html): url = "https://www.fakeurl.com/playlist?list=whatever" request_get.return_value = playlist_html playlist = Playlist(url) playlist._find_load_more_url = MagicMock(return_value=None) links = playlist.parse_links() request_get.assert_called() assert links == [ "/watch?v=ujTCoH21GlA", "/watch?v=45ryDIPHdGg", "/watch?v=1BYu65vLKdA", "/watch?v=3AQ_74xrch8", "/watch?v=ddqQUz9mZaM", "/watch?v=vwLT6bZrHEE", "/watch?v=TQKI0KE-JYY", "/watch?v=dNBvQ38MlT8", "/watch?v=JHxyrMgOUWI", "/watch?v=l2I8NycJMCY", "/watch?v=g1Zbuk1gAfk", "/watch?v=zixd-si9Q-o", ]
def download_videos(addr): try: p_list = Playlist(addr) # 'list' 문자열을 찾지못하면 에러 except KeyError: print('올바른 주소값을 입력해주십시오') return p_list.download_all('./mp3') print('mp4 파일 다운로드를 완료하였습니다.') index = 0 list_len = len(str(len(p_list))) for link in p_list.parse_links(): index += 1 index_str = len(str(index)) if index_str < list_len: index = '0' * (list_len - index_str) + str(index) else: index = str(index) m_addr = 'youtube.com' + link yt = YouTube(m_addr).streams.filter(mime_type="audio/mp4").first() parent_dir = './mp3' default_filename = index + yt.default_filename new_filename = os.path.splitext(default_filename)[0] + '.mp3' print(f'새로운 파일의 이름은 {new_filename}입니다.') subprocess.call([ 'ffmpeg', '-i', os.path.join(parent_dir, default_filename), '-b:a', '192K', '-vn', os.path.join(parent_dir, new_filename) ]) index = int(index) print('mp3 파일 다운로드를 완료하였습니다. mp4 파일을 삭제합니다.') os.remove(os.path.join(parent_dir, default_filename))
def DownloadList(self): VideoPlaylist = Playlist(self.Links) PlaylistLink = VideoPlaylist.parse_links() VideosLink = [] for item in PlaylistLink: VideosLink.append((YouTube("https://www.youtube.com" + item).title, "https://www.youtube.com" + item)) print(VideosLink) if VideosLink: self.tableWidget.setRowCount(0) self.tableWidget.insertRow(0) for row, form in enumerate(VideosLink): for column, item in enumerate(form): self.tableWidget.setItem(row, column, QTableWidgetItem(item)) column += 1 self.tableWidget.insertRow(self.tableWidget.rowCount()) Videos = YouTube("https://www.youtube.com" + PlaylistLink[0]) Dict = {} List = [] Dict["144p"] = [ 1, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='144p').all() ] ] Dict["240p"] = [ 2, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='240p').all() ] ] Dict["360p"] = [ 3, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='360p').all() ] ] Dict["480p"] = [ 4, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='480p').all() ] ] Dict["720p"] = [ 5, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='720p').all() ] ] Dict["1080p"] = [ 6, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='1080p').all() ] ] Dict["1440p"] = [ 7, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='1440p').all() ] ] Dict["2160p"] = [ 8, [ stream.itag for stream in Videos.streams.filter(file_extension='webm', res='2160p').all() ] ] self.comboBox_2.clear() with open('Preferences.txt', 'r') as Preferences: for i in Preferences: List.append(i) Preferences.close() if List[1][17:-1] == "Ask Every Time": self.comboBox_2.clear() self.comboBox_2.addItem("Select Resolution") for resolutions, values in Dict.items(): if values[1]: self.comboBox_2.addItem(resolutions) else: count = Dict[List[1][17:-1]][0] print(count) flag = False while (count > 0): for resolutions, values in Dict.items(): if values[1]: if count == values[0]: self.Resolution = resolutions flag = True break count -= 1 if flag: break self.comboBox_2.clear() self.comboBox_2.addItem("Select Resolution") for resolutions, values in Dict.items(): if values[1]: self.comboBox_2.addItem(resolutions) print(self.Resolution) if self.Resolution == "144p": self.comboBox_2.setCurrentIndex(1) elif self.Resolution == "240p": self.comboBox_2.setCurrentIndex(2) elif self.Resolution == "360p": self.comboBox_2.setCurrentIndex(3) elif self.Resolution == "480p": self.comboBox_2.setCurrentIndex(4) elif self.Resolution == "720p": self.comboBox_2.setCurrentIndex(5) elif self.Resolution == "1080p": self.comboBox_2.setCurrentIndex(6) elif self.Resolution == "1440p": self.comboBox_2.setCurrentIndex(7) elif self.Resolution == "2160p": self.comboBox_2.setCurrentIndex(8)
try: with open('config.yml', 'r') as stream: CONFIG = yaml.load(stream) except Exception as exc: print('Cannot load configuration: %s' % str(exc)) sys.exit(1) # Loading database db = TinyDB('podcastdb.json') # Parse YouTube Playlist and download mp4 files youtube_pl = Playlist(CONFIG['youtube_play_list']) podcast = Query() for link in youtube_pl.parse_links(): if not db.contains(podcast.link == link): try: podcast_filename = 'podcast_%s' % link[9:] video = YouTube('http://youtube.com%s' % link) print('Parsing %s at http://youtube.com%s' % (video.title, link)) video.streams.filter(only_audio=True).all()[0].download( output_path=CONFIG['data_path'], filename=podcast_filename) file_local_path = '%s/%s.mp4' % (CONFIG['data_path'], podcast_filename) db.insert({ 'link': link, 'filename': file_local_path, 'name': video.title }) except HTTPError as err:
import math from pytube import Playlist from pytube import YouTube import os playlistURl = input() pl = Playlist(playlistURl) folder_name = pl.title() Video_List = pl.parse_links() total_size = 1 playlistLen = len(Video_List) folder_path = "" print(folder_name) def create_new_folder(directory): try: if not os.path.exists(directory): os.makedirs(directory) except OSError: print('Error: Creating Folder. ' + directory) def show_progress_bar(stream, chunk, file_handle, bytes_remaining): global total_size total_size = max(bytes_remaining, total_size) print(str(int(100 - (bytes_remaining / total_size * 100))) + "%") return def get_cnt(cnt):
def playlist_download(self, play_list_link, folder_path, quality_max, quality_min): self.folder_path = folder_path playlist_url = play_list_link if playlist_url: pl = Playlist(playlist_url) folder_name = self.filename(pl.title()) video_list = pl.parse_links() self.playlistLen = len(video_list) self.folder_path += folder_name self.create_new_folder(self.folder_path) counter = 1 for x in video_list: print(self.kill_download) if self.kill_download: return self.total_size = 1 try: #with youtube_dl.YoutubeDL(ydl_opts) as ydl: link = "https://www.youtube.com/" + x link_info = ydl.extract_info(link, download=False) print("h5a") y_title = self.filename(link_info['title']) #yt.register_on_progress_callback(self.show_progress_bar) video_name = self.get_cnt(counter) + y_title video_path = video_name + "_v" audio_path = video_name + "_a" if quality_max.text == 'Max Quality': quality_max.text = '2160p' if quality_min.text == 'Min Quality': quality_min.text = '144p' mx_idx = self.max_qualities.index(quality_max.text) mn_idx = self.max_qualities.index(quality_min.text) # ---- Adding Label of Video Title -------- test = f' {y_title} ' print(test) #reshaped_text = arabic_reshaper.reshape(test) #display_text = bidi.algorithm.get_display(reshaped_text) self.video_label = Label(text=f"{counter}. {test}", color=(1, 0.9, 1, 1), size_hint_y=None, height=60, halign="left", valign="middle", size_hint_x=0.6, font_name='Arial') self.video_label.bind( size=self.video_label.setter('text_size')) self.viewerVideo.height += self.video_label.height * 2 self.viewerVideo.add_widget(self.video_label) self.video_folder = Label(text=self.def_directory + folder_name, color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="left", valign="middle", size_hint_x=0.2) self.video_folder.bind( size=self.video_folder.setter('text_size')) self.viewerVideo.add_widget(self.video_folder) self.video_label2 = Label(text="", color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="left", valign="middle", size_hint_x=0.1) self.video_label2.bind( size=self.video_label2.setter('text_size')) self.viewerVideo.add_widget(self.video_label2) test2 = f"0 %" self.video_label3 = Label(text=test2, color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="right", valign="middle", size_hint_x=0.1) self.video_label3.bind( size=self.video_label3.setter('text_size')) self.viewerVideo.add_widget(self.video_label3) # --------------------------------------------------- file_extension_video = "" file_extension_audio = "" video_done = False audio_done = False merge_done = False if self.kill_download: return maxx = quality_max.text.strip('p') minn = quality_min.text.strip('p') ids_quality = "" for k, v in quality_ids.items(): if int(minn) <= int(k) <= int(maxx): for vs in v: ids_quality += f"{vs}/" ydl_opts['format'] = ids_quality print(ids_quality) with youtube_dl.YoutubeDL(ydl_opts) as ydl: meta = ydl.extract_info( 'https://www.youtube.com/watch?v=Vi_xyV3Tj5Q', download=True) #self.video_label2.text = #file_extension_video video_done = True if video_done: try: ydl_opts['format'] = 'bestaudio' with youtube_dl.YoutubeDL(ydl_opts) as ydl: meta2 = ydl.extract_info( 'https://www.youtube.com/watch?v=Vi_xyV3Tj5Q', download=True) #file_extension_audio = sss2[0] audio_done = True except Exception as e: print(f"audio does not exist' {e}") if audio_done and video_done: if MergeVA.merge_va( isinstance, f"{self.folder_path}/{video_path}.{file_extension_video}", f"{self.folder_path}/{audio_path}.{file_extension_audio}", f"{self.folder_path}/{video_name}.mkv"): merge_done = True else: merge_done = False # ---- Changing Label Color if Video is downloaded -------- if merge_done: self.video_label.color = (0.13, 0.83, 0.25, 1) else: self.video_label.color = (1, 0, 0, 1) # --------------------------------------------------------- #caption = yt.captions.get_by_language_code('en') #if caption: # my_file = open(self.folder_path + '/' + self.get_cnt(counter) + y_title + ".srt", "w+", # encoding='UTF8') # my_file.writelines(caption.generate_srt_captions()) # my_file.close() #else: # print("No Sub Found") except Exception as e: print("Can't Download: " + str(e)) # ---- Changing Label Color if Video is not downloaded ---- #self.video_label.color = (1, 0, 0, 1) finally: try: os.remove( f"{self.folder_path}/{video_path}.{file_extension_video}" ) os.remove( f"{self.folder_path}/{audio_path}.{file_extension_audio}" ) except Exception as e: print(f"can't Remove | {e} ") # --------------------------------------------------------- counter += 1
p = percent(self,bytes_remaining, size) def percent(self, tem, total): perc = (float(tem) / float(total)) * float(100) return perc global strms def progress_function(stream, chunk, file_handle, bytes_remaining): global strms print(round((1-bytes_remaining/strms.filesize)*100, 3), '% done...' ,end="\r") urll='https://www.youtube.com/playlist?list=PLWPirh4EWFpG49yASGCmvOwXwVvgnm6Jt' base = "http://www.youtube.com" pl=Playlist(urll) s = pl.parse_links() # strm = yt.streams.all() # yt.download_all(res="720p") full = [] print("Setting links....") for subLink in s: eachLink = base + subLink full.append(eachLink) # for each in full: # yt = YouTube(each, on_progress_callback=progress_function) # strms = yt.streams.filter(res='360p',file_extension='mp4').first() # # ,file_extension='mp4' # # print("Size is : " + getSize(strms.filesize)) # total += int(getSize(strms.filesize)) # # print("Download in progress : " , )
# 无需提前创建播放列表,直接下载youtube 播放列表(<100) import requests import re from pytube import YouTube import os from pytube import Playlist import time import multiprocessing # 定义参数 channel_name = '乒乓生活' # change pl = Playlist("https://www.youtube.com/watch?v=aeGBRfJG7Vs&list=PLnEUh5aDDkHAqYwZeS_Tk-11sV_e-FseO") # change rows = len(pl.parse_links()) start_time = time.time() download_path = os.getcwd() + '\\' + '2_download' + '\\' + channel_name if not os.path.exists(download_path): os.mkdir(download_path) # 增加unicodetoascii函数,去掉异常字符 def unicodetoascii(text): uni2ascii = { ord(b'\xe2\x80\x99'.decode('utf-8')): ord("'"), ord(b'\xe2\x80\x9c'.decode('utf-8')): ord('"'), ord(b'\xe2\x80\x9d'.decode('utf-8')): ord('"'), ord(b'\xe2\x80\x9e'.decode('utf-8')): ord('"'), ord(b'\xe2\x80\x9f'.decode('utf-8')): ord('"'),
def download_YT_audio_list(id): url = 'https://www.youtube.com/playlist?list=' + id pl = Playlist(url) for val in pl.parse_links(): download_YT_audio(val)
def playlist_download(self, play_list_link, folder_path, quality_max, quality_min): self.folder_path = folder_path playlist_url = play_list_link if playlist_url: pl = Playlist(playlist_url) folder_name = self.filename(pl.title()) video_list = pl.parse_links() self.playlistLen = len(video_list) self.folder_path += folder_name self.create_new_folder(self.folder_path) counter = 1 for x in video_list: print(self.kill_download) if self.kill_download: return self.total_size = 1 try: yt = YouTube("https://www.youtube.com/" + x) y_title = self.filename(yt.title) yt.register_on_progress_callback(self.show_progress_bar) video_name = self.get_cnt(counter) + y_title video_path = video_name + "_v" audio_path = video_name + "_a" if quality_max.text == 'Max Quality': quality_max.text = '2160p' if quality_min.text == 'Min Quality': quality_min.text = '144p' mx_idx = self.max_qualities.index(quality_max.text) mn_idx = self.max_qualities.index(quality_min.text) # ---- Adding Label of Video Title -------- test = f' {y_title} ' print(test) #reshaped_text = arabic_reshaper.reshape(test) #display_text = bidi.algorithm.get_display(reshaped_text) self.video_label = Label(text=f"{counter}. {test}", color=(1, 0.9, 1, 1), size_hint_y=None, height=60, halign="left", valign="middle", size_hint_x=0.6, font_name='Arial') self.video_label.bind( size=self.video_label.setter('text_size')) self.viewerVideo.height += self.video_label.height * 2 self.viewerVideo.add_widget(self.video_label) self.video_folder = Label(text=self.def_directory + folder_name, color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="left", valign="middle", size_hint_x=0.2) self.video_folder.bind( size=self.video_folder.setter('text_size')) self.viewerVideo.add_widget(self.video_folder) self.video_label2 = Label(text="", color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="left", valign="middle", size_hint_x=0.1) self.video_label2.bind( size=self.video_label2.setter('text_size')) self.viewerVideo.add_widget(self.video_label2) test2 = f"0 %" self.video_label3 = Label(text=test2, color=(1, 0.9, 1, 1), size_hint_y=None, height=40, halign="right", valign="middle", size_hint_x=0.1) self.video_label3.bind( size=self.video_label3.setter('text_size')) self.viewerVideo.add_widget(self.video_label3) # --------------------------------------------------- file_extension_video = "" video_done = False audio_done = False merge_done = False if self.kill_download: return print(mx_idx, mn_idx) if mx_idx > mn_idx: mx_idx = mn_idx for i in range(mx_idx, mn_idx + 1): try: self.video_label2.text = self.max_qualities[i] yt.streams.filter(adaptive=True, res=self.max_qualities[i]).first(). \ download(self.folder_path, filename=video_path) sss = [ stream.subtype for stream in yt.streams.filter( adaptive=True, res=self.max_qualities[i]).all() ] file_extension_video = sss[0] video_done = True break except Exception as e: print( f"Quality does not exist'| {e} |Quality:{self.max_qualities[i]}" ) if video_done: try: yt.streams.filter( adaptive=True, only_audio=True).first().download( self.folder_path, filename=audio_path) sss2 = [ stream.subtype for stream in yt.streams.filter( adaptive=True, only_audio=True).all() ] print(sss2) file_extension_audio = sss2[0] audio_done = True except Exception as e: print(f"audio does not exist' {e}") if audio_done and video_done: if MergeVA.merge_va( isinstance, f"{self.folder_path}/{video_path}.{file_extension_video}", f"{self.folder_path}/{audio_path}.{file_extension_audio}", f"{self.folder_path}/{video_name}.mkv"): merge_done = True else: merge_done = False # ---- Changing Label Color if Video is downloaded -------- if merge_done: self.video_label.color = (0.13, 0.83, 0.25, 1) else: self.video_label.color = (1, 0, 0, 1) # --------------------------------------------------------- caption = yt.captions.get_by_language_code('en') if caption: my_file = open(self.folder_path + '/' + self.get_cnt(counter) + y_title + ".srt", "w+", encoding='UTF8') my_file.writelines(caption.generate_srt_captions()) my_file.close() else: print("No Sub Found") except Exception as e: print("Can't Download: " + str(e)) # ---- Changing Label Color if Video is not downloaded ---- #self.video_label.color = (1, 0, 0, 1) finally: try: os.remove( f"{self.folder_path}/{video_path}.{file_extension_video}" ) os.remove( f"{self.folder_path}/{audio_path}.{file_extension_audio}" ) except Exception as e: print(f"can't Remove | {e} ") # --------------------------------------------------------- counter += 1
from pytube import Playlist, YouTube mother_playlist = Playlist( "https://www.youtube.com/playlist?list=LLG5oSI03yyAlKazKyyePiMQ") dlist = [] try: dlist = pk.load(open("dlist.pkl", 'rb')) except FileNotFoundError: pass # dlist.append("/watch?v=vOMQsZ47zTk") # dlist.append("/watch?v=Vdjkzij7pdI") for link in mother_playlist.parse_links(): if link not in dlist: print("download https://www.youtube.com%s" % link, end='') try: yt = YouTube("https://www.youtube.com%s" % link) yt.streams.filter(only_audio=True, subtype="mp4").first().download("audio/") dlist.append(link) pk.dump(dlist, open("dlist.pkl", 'wb')) print(" done") except pytube.exceptions.RegexMatchError as e: print(' err\n' + str(e)) except AttributeError as e: print(' err\n' + str(e)) pk.dump(dlist, open("dlist.pkl", 'wb'))