def download_vid(self, target): # try: print(target.text) yt = pytube.YouTube(target.text, on_progress_callback=self.progress_func) Clock.schedule_once(lambda x: yt.streams.first().download(), 4)
for id in instrument_video_ids: total_videos += 1 error_list = [] count = 0 for instrument in instruments_list: instrument_video_ids = list(data['videos'][instrument]) for id in instrument_video_ids: print(id) video_url = 'https://www.youtube.com/watch?v=' + id count += 1 print("Processed Video: ", count, " out of", total_videos, " videos") try: #print("url",video_url) youtube = pytube.YouTube(video_url) video = youtube.streams.first() print("downloading") dump_path = 'data/' + str(instrument) + '/' print("dump path is", dump_path) video.download(dump_path, filename=id) print("finished downloading") except pytube.exceptions.VideoUnavailable: print("unavailable") error_list.append(video_url) except pytube.exceptions.RegexMatchError: print("regex error") error_list.append(video_url)
continue else: vid_src = link['href'] # print(vid_src) # keeping the format of link to be # given to pytube otherwise in some cases new_link = exact_link(vid_src) # error might occur due to this # print(new_link) # appending the link to the links array links.append(new_link) # print(links) # downloading each video from # the link in the links array for link in links: yt = pytube.YouTube(link) # Downloaded video will be the best quality video stream = yt.streams.filter( progressive=True, file_extension='mp4').order_by('resolution').desc().first() try: stream.download() # printing the links downloaded print("Downloaded: ", link) except: print('Some error in downloading: ', link)
# sessions.py를 메모장으로 열고 self.verify = False로 지정하면된다. # 끝 # -*- conding: utf-8 -*- # -*- conding: utf-8 -*- import os import subprocess # pip install pytube3 import pytube from pytube.cli import on_progress import time youtube_address = input( "동영상주소는? (예시: https://www.youtube.com/watch?v=whBV&index=13)") yt = pytube.YouTube(youtube_address, on_progress_callback=on_progress) #다운받을 동영상 URL 지정 vids = yt.streams vids = yt.streams.filter( progressive=True, file_extension='mp4').order_by('resolution').desc().first() download_folder = input("어디에다 저장? (예시: c:\\test) ") #저장 폴더 생성(Windows or mac) try: if not (os.path.isdir(download_folder)): os.makedirs(os.path.join(download_folder)) except OSError as e: if e.errno != errno.EXIST: print("Failed to create directory!!!!!") raise
import pytube import os import subprocess VNum = input("영상 주소? ") yt = pytube.YouTube(VNum) videos = yt.streams.all() print('videos', videos) for i in range(len(videos)): print(i, ' , ', videos[i]) CNum = int(input("화질 선택? ")) down_dir = "C:/Users/analysis/Desktop/youtube" videos[CNum].download(down_dir) newFileName = input('변환할 파일명? ') oriFileName = videos[CNum].default_filename subprocess.call([ 'ffmpeg', '-i', os.path.join(down_dir, oriFileName), os.path.join(down_dir, newFileName) ])
def getVideoTitle(url): return pytube.YouTube(url).title
import pytube ##import tkinter as tk link = input('Enter link of the video: ') done = True point = pytube.YouTube(link) file_formats = point.fmt_streams ##fmt = int(input('1. Video \n2. Audio \n')) sr = 1 for s in file_formats: if s.resolution == None or s.subtype == None: continue if s.type == 'video': print(sr, end='. ') print(s.resolution + ' ' + s.subtype) sr += 1 choice = int(input('Enter resolution: ')) choice -= 1 output_path = input('Enter location where video must be downloaded: ') file_formats[choice].download(output_path) ##elif fmt == 2: ## sr = 1 ## for s in file_formats: ## if s.type == 'audio':
import pytube yt = pytube.YouTube( "https://www.youtube.com/watch?v=aBxsREZinYA") #다운 받을 동영상 URL 지정 videos = yt.streams.all() #print('videos', videos) for i in range(len(videos)): # range (1, 6) 1 이상 6 미만 print(i, ' , ', videos[i]) down_dir = "D:/section2_name/youtube" videos[0].download(down_dir)
hour = time // 3600 time %= 3600 minutes = time // 60 time %= 60 seconds = time return ("%d:%d:%d" % (hour, minutes, seconds)) def views(num): M =str(num) if len(M) >=7: return (M[0]+'.'+M[1]+' M') if len(M)>=4 and len(M)<7: num=num/1000 num=round(num) return str(num)+' K' if len(M)<=3: return num url = input (" type URL :") ytpl = pytube.Playlist(url) print ("number of video of this list are: ",len(ytpl.video_urls)) total=0 for link in ytpl.video_urls: youtube=pytube.YouTube(link) # video = youtube.streams.get_highest_resolution() print ( youtube.title," video time =>",sec2hm(youtube.length) ,"rating => ",round(youtube.rating,1) ,"views =>",views(youtube.views)) total+=youtube.length print ("total time is", sec2hm(total) ,"hours") #video.download()
import pytube import os import subprocess yt = pytube.YouTube("https://www.youtube.com/watch?v=AeXo05Iull0") videos = yt.streams.all() for item in range(len(videos)) : print(item, ', ', videos[item]) down_dir = "D:\psp" cNum = int(input("다운 받을 화질은?? (0~21)")) videos[cNum].download(down_dir) newFileName = input("변환 할 파일명은??") oriFileName = videos[cNum].default_filename subprocess.call(['ffmpeg', '-i', os.path.join(down_dir, oriFileName), os.path.join(down_dir, newFileName) ]) print("동영상 다운로드 및 mp3 변환 완료!!!")
import pytube def __convert(): new_filename = input("[+]변환할 확장자는?") default_filename = vids[vnum].default_filename subprocess.call([ 'ffmpeg', '-i', os.path.join(parent_dir, default_filename), os.path.join(parent_dir, new_filename) ]) pass try: yt = pytube.YouTube(input("download URL : ")) vids = yt.streams.all() except: print("[+]저작권에 의해 다운로드가 막힌 영상입니다.") quit() for i in range(len(vids)): print( "번호 : [", i, '] ' + '확장자 및 화질: {}'.format( str(vids[i]) [str(vids[i]).find("mime_type=\""):str(vids[i]).find("fps")])) vnum = int(input("화질 번호 입력 : ")) try: print("[+] Loding....") vids[vnum].download(os.getcwd().replace("\\", "/"))
import pytube #下载视频地址 my_url = "https://www.youtube.com/watch?v=QJ7EVRvRDas&t=20s" #下载 pytube.YouTube(my_url).streams.filter( only_audio=False, file_extension="mp4")[0].download(output_path="E:/", filename="my_audio")
def main(args): global fileName, url, PATH, videoType url = args.u videoType = args.f PATH = args.P fileName = args.o t1 = time() # ____________________________________ print("[+]Connecting to youtube") try: youtube = pytube.YouTube(url) videoLength = youtube.length print("[+]connected") print(f"[+]Title: {youtube.title}") print(f"[+]Length: {videoLength/60}m") except Exception as e: print("[-]Unable to connect youtube") sys.exit() if fileName == "untitle": fileName = youtube.title # ____________________________________ try: if videoType == "mp3" or videoType == "audio": video = youtube.streams.last() print(f"[+]Type: mp3") print("\n") print( "######################################### Description ####################################" ) print("\n") print(youtube.description) elif videoType == "mp4" or videoType == "video": video = youtube.streams.first() print(f"[+]Type: mp4") print("\n") print( "######################################### Description ################################################" ) print("\n") print(youtube.description) elif videoType == "-h": print(f"[+]Video types: mp3 or mp4") quit() else: print("[-]Invalied video type") print("[-]-h for help") quit() except Exception as TypeError: print("[-]Invalied video type") sys.exit() # ____________________________________ print( "#########################################################################################" ) print("\n") print(f'[+]Saving as {fileName}.{videoType}') # ____________________________________ if PATH == "": print(f"[+]Saving at {os.getcwd()}") PATH = os.getcwd() else: print(f"[+]Saving at {PATH}") # ____________________________________ pun = string.punctuation digit = string.digits list1 = [] list1.extend(pun) list1.extend(digit) for item in list1: fileName = fileName.replace(item, "") try: print("[+]Downloading please wait.......") video.download(PATH, fileName) except Exception as e: print(e) print("[-]Falied to download") sys.exit() # ____________________________________ fileName = fileName + '.webm' # ____________________________________ sleep(5) if videoType == "mp3" or videoType == "audio": print("[+]Converting.......") flac_audio = AudioSegment.from_file(f"{PATH}/{fileName}") flac_audio.export(f"{PATH}/{fileName[:-5]}" + ".mp3", format="mp3") # ____________________________________ print("[+]Download completed") t2 = time() print(f"[+]Finished in {t2-t1}s") sys.exit() quit()
import pytube import os import subprocess youtubeurl = input("url:") yt = pytube.YouTube(youtubeurl) videos = yt.streams.all() for i in range(len(videos)): print(i, videos[i]) cnum = int(input("select the video quility(0~16)")) down_dir = "C:\\Users\\moon2\\Desktop\\file\\py\\s2" videos[cnum].download(down_dir) newfilename = input("new file name?") orifilename = videos[cnum].default_filename subprocess.call([ 'ffmpeg', '-i', os.path.join(down_dir, orifilename), os.path.join(down_dir, newfilename) ])
if (input(">SET VIDEO QUALITY >> '1' => 720p -<OR>- '2' => 360p) : ") == "1"): TAG = 22 else: TAG = 134 print("\n>SIT BACK AND RELAX AND LET ME SERVE YOU! ;)") print("\n>YOUR INTERNET SPEED :", '%.2f' % (speed), "mbps") print( "\n\n==============================================<< Active Session:", session, " >>========================================================") for i in range(0, sizeu): youtube = pytube.YouTube(urlist[0][i], on_progress_callback=progress_function) video = youtube.streams.get_by_itag(TAG) print("\n>DOWNLOADING NOW : VIDEO ID: ", (i + 1), " ------------------------------>") try: size = video.filesize / 1e+6 title = youtube.title print("\n->Video Url : " + urlist[0][i]) print("->Video Title : ", title) print("->Video Length : ", '%.2f' % (youtube.length / 60), "minutes") # print("->Video Description : ", youtube.description) print("->Video Size : ", '%.2f' % (size), "MB") print("->Estimated Time to Download : ", '%.2f' % (size / (speed / 0.125)), "minutes")
#%% import ScoreFollow from importlib import reload reload(ScoreFollow) sf = ScoreFollow.ScoreFollow() cqtfeatures = sf.wav2features(wav_obj, 'cqt') censfeatures = sf.wav2features(wav_obj, 'cens') melfeatures = sf.wav2features(wav_obj, 'mel') stftfeatures = sf.wav2features(wav_obj, 'stft') mfccfeatures = sf.wav2features(wav_obj, 'mfcc') polyfeatures = sf.wav2features(wav_obj, 'poly') #%% import pytube yt = pytube.YouTube(sf.youtube) stream = yt.streams.filter(only_audio=True).order_by('bitrate').asc().first() stream.download() #%% import os os.chdir(r'C:\Users\Niki\Source\SmartSheetMusic') import ScoreFollow from importlib import reload reload(ScoreFollow) sf = ScoreFollow.ScoreFollow() for i in range(16): sf.offline_follow(i)
# pip install pytube import pytube url = input("Enter Your YouTube link...\n") video = pytube.YouTube(url) stream = video.streams.get_by_itag( 22) # 22 is for Downloading 720p videos only. print("DOWNLOADING YOUR VIDEO>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") stream.download(filename=f"{input('Enter your file name... ')}") print("DONE>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") '''for stream in video.streams: if "video" in str(stream) and "mp4" in str(stream): print(stream) '''
import pytube linke = input("Enter the URL linke:") video = pytube.YouTube(linke) opt = 0 vid = video.streams.all() for i in video.streams.all(): print(str(opt) + ". " + str(i)) opt = opt + 1 vid = vid[int(input("enter number:"))] path = input("Enter the path:") vid.download(path)
import pytube url = 'https://www.youtube.com/watch?v=Wc_rsE0VJQg' youtube = pytube.YouTube(url) streams = youtube.streams.all() for i in streams: # Retorna as resoluções do vídeo print(i) video = youtube.streams.get_by_itag(22) video.download() print('Download Completo!')
def __init__(self, user: str, url: str, audio_path="music/", thumbnail_path="picture/"): self._path_assign(user, audio_path, thumbnail_path) self.user = user self.youtube_object = pytube.YouTube(url) self.title = "".join(filter(lambda x: x if x not in "~\"\'#%&*:<>?\/{|},\." else False, self.youtube_object.title)) self.audio_object = self.youtube_object.streams.filter(only_audio=True, file_extension='mp4').fmt_streams[0]
class vid: """ vid: vid is an object that contains all the values to be returned for a search of the keyword in Adam Norris' APUSH Videos. It returns the following to the user: vid.err: an error code. if "nil", no error was returned. if "disarmament", there were more than one videos returned. if "pageantry", no video was found. vid.unit: the unit that the video is part of vid.timeperiod: the time period the video is a part of vid.link: a link to the YouTube video itself vid.title: the title of the video vid.content: the description """ try: # query all unit captions, return time period. then query unit.video captions, return title, and url units = [ units.unit1, units.unit2, units.unit3, units.unit4, units.unit5, units.unit6, units.unit7, units.unit8, units.unit9 ] for u in units: found = re.findall(str(querylower), str(u.captions).lower()) if found == [] and len(found) > 1: err = "disarmament" unit = str(u) break elif found == [] and len(found) == 0 or found == None: err = 'pageantry' unit = None else: unit = str(u).split(".") unit = unit[2].split("'>") unit = unit[0] err = 'nil' break if unit == None: err = 'pageantry' else: videos, subjectvideo, dontuse, notelinks, daterange, vocab = unitdb( unit) if err == 'nil': timeperiod = daterange count = -1 for i in subjectvideo: count = int(count + 1) vidfound = re.findall(str(querylower), str(i).lower()) if vidfound != None: link = str(videos[count]).replace("'", "") videobj = pytube.YouTube(link) description = videobj.description title = videobj.title content = f"\n{description}\n" break else: err == 'pageantry' if err == 'disarmament': relevant = videos if err == 'pageantry': pass except: err = 'u-noun' pass
import pytube youtube = pytube.YouTube(input("Cole aqui o link do vídeo: ")) # URL para você testar: https://www.youtube.com/watch?v=RRkIQ1Djlbs print("\nÉ um vídeo restrito:", youtube.age_restricted) #Se existe restrição de idade print("Data:", youtube.publish_date) #Exibe a data de publicação do vídeo print("Duração: {} minutos e {} segundos".format(youtube.length//60, youtube.length%60)) #Exibe a extensão do vídeo em segundos print("Palavras chaves:", youtube.keywords) #Exibe as palavras chaves associadas ao vídeo print("Descrição:", youtube.description) #Exibe a descrição do vídeo (feita pelo autor) print("Autor:", youtube.author) #Exibe o autor (nome do canal) print("Título:", youtube.title) #Exibe o título do vídeo print("Visualizações:", youtube.views) #Exibe o número de views do vídeo input("\nAperte ENTER para sair...")
import os import subprocess import pytube yt = pytube.YouTube("https://youtu.be/CTRO5NXmAp8") vids = yt.streams.all() for i in range(len(vids)): print(i, ',', vids[i]) down_dir = "D:/gms/Atom" vids[0].download(down_dir)
import pytube print("Enter video URLs") videos = [] while True: url = input("") if url == "OKAY": break videos.append(url) for indexnum, video in enumerate(videos): down = pytube.YouTube(video) stream = down.streams.get_by_itag(22) print(f"Downloading video {indexnum}") stream.download() print("The download is complete")
import pytube import os import subprocess yt = pytube.YouTube("https://www.youtube.com/watch?v=fi6e6wGrjsE") videos = yt.streams # print('videos', videos) for i in range(len(videos)): print(i, ', ', videos[i]) input_num = int(input("화질은?")) down_dir = "C:/crawling/youtube" videos[input_num].download(down_dir) new_file_name = input("변환 파일 명?") org_file_name = videos[input_num].default_filename print(os.path.join(down_dir, org_file_name)) print(os.path.join(down_dir, new_file_name)) # 커맨드 콜 subprocess.call([ 'ffmpeg', '-i', os.path.join(down_dir, org_file_name), os.path.join(down_dir, new_file_name) ])
def saveVideo(videoLink): yt = pytube.YouTube(videoLink) yt.streams.first().download() return yt.title
import os import subprocess import pytube # 설운도 https://www.youtube.com/watch?v=WW2vcbBkyRk&list=WL # 김건모 https://www.youtube.com/watch?v=Boz6QhrxE8E&list=WL&index=2&t=0s # 홍진영 https://www.youtube.com/watch?v=xHCFLeei5Wg&list=WL&index=3 # 싸이 https://www.youtube.com/watch?v=9bZkp7q19f0&list=WL&index=4 # 터보 https://www.youtube.com/watch?v=Ngyjoe86hPg&list=WL&index=5 # 깅연자 https://www.youtube.com/watch?v=MPX-ojIEbDI&list=WL&index=7 target = "https://www.youtube.com/watch?v=WW2vcbBkyRk&list=WL" yt = pytube.YouTube(target) vids = yt.streams.all() for i in range(len(vids)): print("번호 {} - {}".format(i, vids[i])) vnum = int(input("번호선택: ")) parent_dir = "D:\\workspaces\\download\\" new_name = input("파일명 입력: ") org_name = vids[vnum].default_filename subprocess.call([ 'ffmpeg', '-i', os.path.join(parent_dir, org_name), os.path.join(parent_dir, new_name) ]) print("완료")
def robat(self, *, audio_text=None): if audio_text is None: text = self.Titlebox.text() else: text = audio_text if '192.168' in text: self.capture() elif text == 'hello': engine.say('Hello My friend') engine.say('How Rosette passed ?') engine.runAndWait() elif text == 'Yes, I had a good day': engine.say('OK') engine.runAndWait() elif text.split()[0] in ('google', 'Google', 'bmbgk'): # google search engine.say('OK') engine.runAndWait() google_text = '' google_search = text.split()[1:] for search in google_search: google_text += search google_text += ' ' webbrowser.open('http://bmbgk.ir/?q={0}'.format(google_text)) elif text.split()[0] in ('youtube', 'Youtube'): # youtube search engine.say('OK') engine.runAndWait() youtube_search = text.split()[1:] youtube_text = '' if youtube_search == []: webbrowser.open('https://www.youtube.com/') else: for search in youtube_search: youtube_text += search youtube_text += ' ' webbrowser.open( 'https://www.youtube.com/results?search_query={0}'.format( youtube_text)) elif 'youtu.be' in text: # download youtube url = self.Titlebox.text() path = 'C:\\Users\\User\\Desktop\\Download Youtube' engine.say('Download now') engine.runAndWait() try: if os.path.isdir(path): youtube = pytube.YouTube(url) video = youtube.streams.first() video.download(path) else: os.mkdir(path) youtube = pytube.YouTube(url) video = youtube.streams.first() video.download(path) engine.say('Finished download') engine.runAndWait() except: engine.say("I can't download") engine.say('You must use a VPN') engine.runAndWait()
# TODO : not working # from datakund import * # youtube=datakund.youtube() # # # * get search results * # youtube.search_results() # # {“body”: [{‘viewsandtime’: ‘viewsandtime’, ‘channel’: ‘channel’, ‘title’: ‘title’, ‘link’: ‘link’}], “success_score”: “100”, “errors”: []} url = 'https://www.youtube.com/watch?v=4SFhwxzfXNc' # * get video infos * # youtube.get_video_info(video_url=url) # # TODO : use it #{“body”: {‘DisLikes’: ‘DisLikes’, ‘Title’: ‘Title’, ‘Subscribers’: ‘Subscribers’, ‘Comments’: ‘Comments’, ‘ChannelLink’: ‘ChannelLink’, ‘ChannelName’: ‘ChannelName’, ‘Desc’: ‘Desc’, ‘Views’: ‘Views’, ‘Duration’: ‘Duration’, ‘Publish_Date’: ‘Publish_Date’, ‘Likes’: ‘Likes’}, “success_score”: “100”, “errors”: []} # * download comments * # youtube.open(url) # youtube.keypress("pagedown") # response = youtube.video_comments() # data = response['body'] # # for d in data: # print(d['Comment']) # print(d['Likes']) # print(d['Time']) # print(d['UserLink']) # * download video files for violence automatic analysis * print(pytube.YouTube(url).streams.get_lowest_resolution().download('/tmp'))
def get_fetch(): resolution = Rvideo.get() Select = A_Video.get() Selection = A_Audio.get() try: update_check() except r.exceptions.HTTPError as err: # - No Updates messagebox.showinfo("FYIT", "Select Location to Save the File.") except r.ConnectionError as e: messagebox.showinfo("Connection Error", "Check the Internet Connection") try: if var1 is None: print("error") dirname = filedialog.askdirectory(parent=tab1, initialdir="/", title='Please select a directory:') if dirname: try: # Youtube Video with Resolution if resolution <= 3: yt = pytube.YouTube(var1.get()) if resolution == 1: progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() messagebox.showinfo( "Download", "Downloading.. Please Wait for a Minute.") video = yt.streams.get_by_itag(22) video.download(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") elif resolution == 2: progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() messagebox.showinfo("Download", "Downloading...") video = yt.streams.first() video.download(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") elif resolution == 3: progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() messagebox.showinfo("Download", "Downloading...") video = yt.streams.get_by_itag(36) video.download(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") # Download Playlist if Select == 1: playlist = pytube.Playlist(var1.get()) progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() playlist.populate_video_urls() # To load bulk list messagebox.showinfo("Download", "Downloading...") playlist.download_all(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") # Audio files if Selection <= 2: link = YouTube(var1.get()) format_a = link.streams.filter(only_audio=True).all() if Selection == 1: # mp4 progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() messagebox.showinfo("Download", "Downloading...") format_a[0].download(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") elif Selection == 2: # webm progress_bar = ttk.Progressbar(tab1, orient='horizontal', length=500, mode='determinate') progress_bar.place(x=70, y=160) progress_bar.start() messagebox.showinfo("Download", "Downloading...") format_a[1].download(dirname) messagebox.showinfo("Downloaded. ", "Thank You..") messagebox.showinfo("FYIT", "Please Select Valid option") except Exception as a: messagebox.showwarning(" FYIT.. ", "Failed") else: messagebox.showwarning(" FYIT. ", "Cancelled") except Exception as a: messagebox.showwarning(" FYIT. ", "Cancelled") sys.exit()