本文整理汇总了Python中pytube.YouTube.filter方法的典型用法代码示例。如果您正苦于以下问题:Python YouTube.filter方法的具体用法?Python YouTube.filter怎么用?Python YouTube.filter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytube.YouTube
的用法示例。
在下文中一共展示了YouTube.filter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_song_info
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def get_song_info(given_url="", local_dir=cur_dir, quality=1):
"""Returns song info for given YouTube url"""
url = is_valid_youtube_url(given_url)
yt = YouTube(url)
raw_info = yt.get_video_data()
if 'args' in raw_info:
song_info = copy.copy(empty_record)
song_info['url'] = url
song_info['title'] = raw_info['args']['title']
song_info['author'] = raw_info['args']['author']
try:
song_info['video_id'] = raw_info['args']['vid']
except KeyError:
song_info['video_id'] = url.replace(youtube_base_url, '')
song_info['duration'] = int(raw_info['args']['length_seconds'])
song_info['view_count'] = int(raw_info['args']['view_count'])
song_info['thumbnail_url'] = raw_info['args']['thumbnail_url']
filter_index = get_filter_index(quality, len(yt.filter()))
video = yt.filter()[filter_index]
local_file_name = "{0}.{1}".format(yt.filename, video.extension)
local_file_path = os.path.join(local_dir, local_file_name)
if os.path.exists(local_file_path):
song_info['local_file_path'] = local_file_path
return song_info
else:
return None
示例2: _download_file
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def _download_file(self, video_id):
file_path = self._build_file_path(video_id)
if not os.path.isfile(file_path):
yt = YouTube()
yt.from_url("http://youtube.com/watch?v=" + video_id)
yt.filter('mp4')[0].download(file_path) # downloads the mp4 with lowest quality
return file_path
示例3: down
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def down(url, directory=None, skippable=False, ftype=None):
if not directory:
directory = os.getcwd()
try:
yt = YouTube(url)
except:
print('Could not get URL "{}"'.format(url))
return
yt.get_videos()
print('Found "{}"'.format(yt.filename))
if skippable and input("Download? [y]/n: ") not in ['','y']:
return
if len(yt.filter(resolution='480p')) == 0:
if len(yt.filter(resolution='360p')) == 0:
print("Can't find 480p or 360p: {}".format(yt.filename))
return
video = yt.get('mp4', '360p')
else:
video = yt.get('mp4', '480p')
try:
video.download(os.getcwd())
print('...download finished')
except OSError:
print("Could not write file")
if ftype == 'mp3':
fname = video.filename
mp4_to_mp3(fname, directory)
示例4: Download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def Download(songURI, bestQuality = False):
filetype = "mp4"
#Check if NAS is mounted
nasDir = '/home/pi/music/yt/'
bckDir = '/home/pi/musicBAK/'
dirUse = nasDir
if os.path.isdir(nasDir):
#put bck files into nasDirs
bakFiles = os.listdir(bckDir)
for x in range(0,len(bakFiles)):
shutil.copy(bckDir+bakFiles[x], nasDir+bakFiles[x])
os.remove(bckDir+bakFiles[x])
else:
dirUse = bckDir
#if input is null then return
if songURI == "":
return
songURL = "https://www.youtube.com/watch?v="+songURI
#use full url if that is given
if "youtube.com" in songURI:
songURL = songURI
try:
yt = YouTube(songURL)
except:
print "ERROR: URL is not a video!"
if bestQuality:
video = yt.filter(filetype)[-1]
else :
video = yt.filter(filetype)[0]
print "starting download to '" + dirUse + "'";
try:
video.download(dirUse);
print "down succeeded"
except:
print "download failed:", sys.exc_info()
if dirUse == nasDir:
client = MPDClient() # create client object
client.connect("localhost", 6600) # connect to localhost:6600
#client.update("yt/"+yt.filename + "."+filetype)
#Hack so that it will wait for the fucking update.
call(["mpc", "update",("yt/"+yt.filename+"."+filetype),"-w"])
client.disconnect()
time.sleep(0.1);
return yt.filename + "."+filetype
示例5: download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download(video_id):
yt = YouTube()
yt.from_url(construct_url(video_id))
yt.set_filename(video_id)
first_video = yt.filter(resolution='480p') + yt.filter(resolution='360p')
if not len(first_video):
return False
first_video[0].download(MEDIA_URL)
return True
示例6: download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download(video_url_or_id, folder_path = "./"):
if "youtube.com" in video_url_or_id:
video_id = video_url_or_id.split("v=")[-1]
elif "youtu.be" in video_url_or_id:
video_id = video_url_or_id.split(".be/")[-1]
else:
video_id = video_url_or_id
video_id = re.search("[\w-]+", video_id).group(0)
yt = YouTube()
yt.from_url("http://www.youtube.com/watch?v={}".format(video_id))
yt.filter("mp4")[-1].download(path = folder_path, force_overwrite = True)
示例7: dl_video
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def dl_video(link):
print("Downloading [" + link + "]")
try:
yt = YouTube(link)
yt.filter('mp4')[-1].download('./')
print("Done [" + link + "] (" + yt.filename + ")")
return yt.filename
except:
print("Could not download: " + link)
print(sys.exc_info()[0])
return False
示例8: downloadFisicalFile
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def downloadFisicalFile(youtubeId, idName):
yt = YouTube()
yt.url = ("http://www.youtube.com/watch?v=" + youtubeId)
yt.filename = idName
video = 0
if len(yt.filter('mp4')) > 0:
if len(yt.filter(resolution='720p')) > 0:
video = yt.get('mp4','720p')
else:
video = yt.get('mp4')
video.download("tempvideo/")
else:
cocomo.printJson("no se puede descargar el archivo", "error")
示例9: download_song
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download_song(given_url="", local_dir=cur_dir, quality=1):
"""
Downloads the video song for given YouTube URL
to the given local_dir (default os.getcwd()) of given quality
"""
url = is_valid_youtube_url(given_url)
yt = YouTube(url)
filter_index = get_filter_index(quality, len(yt.filter()))
video = yt.filter()[filter_index]
local_file_name = "{0}.{1}".format(yt.filename, video.extension)
local_file_path = os.path.join(local_dir, local_file_name)
if not os.path.exists(local_file_path):
video.download(local_dir)
return local_file_path
示例10: download_single_video
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download_single_video(save_dir, video_url):
yt = YouTube(video_url)
try:
video = min(yt.filter('mp4'))
except:
video = min(yt.get_videos())
# save_dir = "video/" + label + "/"
if not (os.path.isdir(save_dir)):
os.mkdir(save_dir)
valid_chars = "-_ %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in yt.filename if c in valid_chars)
filename = filename.replace('-','_')
filename = filename.replace(' ','_')
while(filename[-1] == '_'):
filename = filename[:-1]
if(os.path.isfile(save_dir + filename + '.' + video.extension)):
return
yt.set_filename(filename)
video.download(save_dir)
示例11: download_Video_Audio
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download_Video_Audio(path, vid_url, file_no):
try:
yt = YouTube(vid_url)
except Exception as e:
print("Error:", str(e), "- Skipping Video with url '"+vid_url+"'.")
return
try: # Tries to find the video in 720p
video = yt.get('mp4', '720p')
except Exception: # Sorts videos by resolution and picks the highest quality video if a 720p video doesn't exist
video = sorted(yt.filter("mp4"), key=lambda video: int(video.resolution[:-1]), reverse=True)[0]
print("downloading", yt.filename+" Video and Audio...")
try:
bar = progressBar()
video.download(path, on_progress=bar.print_progress, on_finish=bar.print_end)
print("successfully downloaded", yt.filename, "!")
except OSError:
print(yt.filename, "already exists in this directory! Skipping video...")
try:
os.rename(yt.filename+'.mp4',str(file_no)+'.mp4')
aud= 'ffmpeg -i '+str(file_no)+'.mp4'+' '+str(file_no)+'.wav'
final_audio='lame '+str(file_no)+'.wav'+' '+str(file_no)+'.mp3'
os.system(aud)
os.system(final_audio)
os.remove(str(file_no)+'.wav')
print("sucessfully converted",yt.filename, "into audio!")
except OSError:
print(yt.filename, "There is some problem with the file names...")
示例12: download_videos
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def download_videos(test=True):
manually_download = []
positions = Week.objects.all()[0].position_set.all().order_by('position')
songs = [p.song for p in positions][50:]
for song in songs:
if song.youtube_link:
link = 'http://www.youtube.com/watch?v=' + song.youtube_link
try:
yt = YouTube(link)
yt.set_filename("{} - {}".format(song.name, song.artist.name))
except AgeRestricted:
manually_download.append(link)
print 'Song is age restricted, adding to manually_download list.'
continue
try:
video_type = yt.filter('mp4')[-1]
video = yt.get(video_type.extension, video_type.resolution)
except Exception:
traceback.print_exc()
continue
if not os.path.exists(os.path.abspath(os.path.join(settings.RAW_VIDEOS, video.filename + ".mp4"))):
print 'Downloading video: {} - {}'.format(song, video_type.resolution)
video.download(settings.RAW_VIDEOS)
else:
print 'Video: {} already downlaoded. Skipping.'.format(song)
print 'Manually download these songs: %s' % manually_download
示例13: downloadSong
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def downloadSong(url):
video = pafy.new(url)
best = video.getbest(preftype="mp4")
yt = YouTube()
yt.url = url
os.system('cls') # os.system('clear') for linux.
print "Download URL fetched successfully!\n"
print "1. Get the list of available streams"
print "2. Get the highest resolution available"
print "3. Start download the video\n"
while True:
print "Select an action: "
action = raw_input("> ")
if action == str(1):
print "Availabile streams for the URL: \n"
pprint(yt.videos)
print "\n"
elif action == str(2):
print "Highest resolution is:"
pprint(yt.filter('mp4')[-1])
print "\n"
elif action == str(3):
print "Starting download: \n"
best.download(quiet=False)
print "Download finished!, the file has been downloaded to the same folder where the script is located."
sys.exit(0)
else:
print "Not a valid option!\n"
示例14: downloadVideo
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def downloadVideo(url, codec):
try:
yt = YouTube(url)
vidName = str(yt.filename)
start_time = time.time()
if codec == 0:
print "(+) Codec: MP4"
allVidFormat = yt.get_videos()
higMp4Res = str(yt.filter('mp4')[-1]).split()[-3]
print "\n(+) Name: %s" %vidName
print "(+) URL: %s" %url
print "(+) Resolution: %s" %higMp4Res
video = yt.get('mp4', higMp4Res)
print "(+) Downloading video"
video.download('.')
print "(+) Download complete"
if codec == 1:
print "[youtube] Codec: MP3"
ydl = youtube_dl.YoutubeDL()
r = ydl.extract_info(url, download=False)
options = {'format': 'bestaudio/best', 'extractaudio' : True, 'audioformat' : "best", 'outtmpl': r['title'], 'noplaylist' : True,}
print "[youtube] Name: %s" % (vidName)
print "[youtube] Uploaded by: %s" % (r['uploader'])
print "[youtube] Likes: %s | Dislikes: %s" % (r['like_count'], r['dislike_count'])
print "[youtube] Views: %s" % (r['view_count'])
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download([url])
print("[youtube] Download Time: %s sec" % round((time.time() - start_time), 2))
print ""
except Exception as e:
print "(-) Error: %s" %e
示例15: fetch_video_by_url
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import filter [as 别名]
def fetch_video_by_url(self, url):
'''Fetch video by url
:param [str] url:
The url linked to a YouTube video
'''
yt = YouTube(url)
if(self.resolution == 'highest' or self.resolution == 'lowest'):
video_list = yt.filter(self.extension)
if(len(video_list) == 0):
raise DoesNotExist("No videos met this criteria.")
if(self.resolution == 'highest'):
video = video_list[-1]
else:
video = video_list[0]
else:
result = []
for v in yt.get_videos():
if self.extension and v.extension != self.extension:
continue
elif self.resolution and v.resolution != self.resolution:
continue
else:
result.append(v)
matches = len(result)
if matches <= 0:
raise DoesNotExist("No videos met this criteria.")
elif matches == 1:
video = result[0]
else:
raise MultipleObjectsReturned("Multiple videos met this criteria.")
return video