本文整理汇总了Python中pytube.YouTube.set_filename方法的典型用法代码示例。如果您正苦于以下问题:Python YouTube.set_filename方法的具体用法?Python YouTube.set_filename怎么用?Python YouTube.set_filename使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytube.YouTube
的用法示例。
在下文中一共展示了YouTube.set_filename方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_videos
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [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
示例2: download_single_video
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [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)
示例3: updateUi
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def updateUi(self):
self.outtext.append("Download has started!!")
yt = YouTube()
yt.from_url(self.intext.toPlainText())
yt.set_filename("Temp")
video = yt.videos[0]
video.download()
self.outtext.append("Download Finished!!")
pass
示例4: download_youtube
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download_youtube(url, timeout=0, chunk_size=config.DEFAULT_CHUNKSIZE):
def _cleanup_filename(path):
# removes the container type from the movie file
# filename, placed automatically by pytube module.
# this is an ``on_finish`` callback method from Video.download(..)
pre, ext = os.path.splitext(path)
os.rename(path, pre)
def _sort_by_quality(v_list):
# give better codecs a higher score than worse ones,
# so that in resolution ties, the better codec is picked.
boost = {
'webm': 1.2,
'mp4': 1.1,
'flv': 1.0,
'3gp': 0.7}
video_scores = dict()
for v in v_list:
score = int(v.resolution.strip('pP')) * boost.get(v.extension.lower(), 0.9) + int(v.audio_bitrate)
video_scores[score] = v
return video_scores
url = url.get('url', None)
if not url:
return None
logger.info('downloading (youtube) video: ' + url)
try:
# get our Youtube Video instance given a url
yt = YouTube(url)
# generate a new temp movie name, so we can set the download
# filename..and point the ``video.get(..)`` to the ``path`` portion.
fullpath = gen_filename(config.DROP_FOLDER_LOCATION, extension='movie')
path, name = os.path.split(fullpath)
yt.set_filename(name)
# no built in way to get BEST video option
video_formats = _sort_by_quality(yt.get_videos())
highest_quality = sorted(video_formats.items(), reverse=True)[0][1] # [(score, Video<inst>), .., ..]
# download that shit
video = yt.get(highest_quality.extension, highest_quality.resolution, profile=highest_quality.profile)
video.download(path, chunk_size=chunk_size, on_finish=_cleanup_filename)
except Exception as e:
# something went wrong...
logger.error(e)
return None
else:
# if the new file path is there, then it completed successfully,
# otherwise return ``None`` to handle an error case given our JSON.
return True if os.path.exists(fullpath) else None
示例5: download_links
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download_links(linkList, pathWrite):
''' Download the links '''
name_num = 0
for l in linkList:
y = YouTube(l)
y.set_filename(str(name_num))
video = y.get('mp4', '720p')
video.download(pathWrite)
name_num += 1
示例6: download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [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
示例7: downloadVideo
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def downloadVideo(self, videoList):
ytVideo = videoList[0]
yt = Ytdwn("http://www.youtube.com/watch?v=%s"%ytVideo._ident)
filename = 'YT_%s' % ytVideo._ident
yt.set_filename(filename)
video = yt.filter(resolution='360p')[0]
filepath = "%s/%s.%s" % (YOUTUBE_VIDEOS_LOCATION, filename, video.extension)
if os.path.exists(filepath):
os.remove(filepath)
video.download(YOUTUBE_VIDEOS_LOCATION)
ytVideo._file_path = filepath
ytVideo.save()
示例8: download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download(self):
"""
Downloads the YouTube video and sets the video's title.
"""
yt = YouTube('https://www.youtube.com/watch?v={0}'.format(self.youtube_id))
video = yt.filter('mp4')[-1]
self.title = video.filename
self.file_path = '{0}.mp4'.format(self.youtube_id)
yt.set_filename(self.youtube_id)
video.download(settings.YOUTUBE_DOWNLOAD_ROOT)
self.downloaded = True
self.save()
示例9: download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download(link, path="video_index/"):
yt = YouTube(link)
file_name = re.sub(r'\W+', '',
yt.filename.replace(" ", "_")) # Ugly ass solution to fix encoding errors later on...
yt.set_filename(file_name)
video_path = os.path.join(path, yt.filename)
print "Downloading video: " + yt.filename
# Below downloads the video in the lowest resolution available.
# Change the '0' to '-1' to get the highest instead
video = yt.filter('mp4')[VIDEO_RESOLUTION]
video.download(path)
return video_path
示例10: download_links
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download_links(linkList, pathWrite):
''' Download the links '''
name_num = 0
for l in linkList:
y = YouTube(l)
y.set_filename(str(name_num))
try:
video = y.get('mp4', '720p')
video.download(pathWrite)
name_num += 1
except:
print("Video " + l + " does not meet criteria (mp4,720p)")
示例11: download_and_process_video
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def download_and_process_video(save_path, row):
video_id = row["VideoID"]
video_path = row["video_path"]
full_path = os.path.join(save_path, video_path)
if os.path.exists(full_path):
return
start = row["Start"]
end = row["End"]
print video_id
if os.path.exists("tmp.mp4"):
os.system("rm tmp.mp4")
try: # 다운로드 포기
youtube = YouTube("https://www.youtube.com/watch?v=" + video_id)
except:
print "다운로드 포기"
return
youtube.set_filename("tmp")
try: # 360p로 받아보고 안되면 예외처리
video = youtube.get("mp4", "360p")
except:
ipdb.set_trace()
video.download(".")
cap = cv2.VideoCapture("tmp.mp4")
fps = cap.get(cv.CV_CAP_PROP_FPS)
fourcc = int(cap.get(cv.CV_FOURCC(*"XVID")))
w = int(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH))
h = int(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT))
out = cv2.VideoWriter(full_path, fourcc, fps, (w, h))
start_frame = int(fps * start)
end_frame = int(fps * end)
frame_count = 0
while frame_count < end_frame:
ret, frame = cap.read()
frame_count += 1
if frame_count >= start_frame:
out.write(frame)
cap.release()
out.release()
示例12: downloadVideo
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def downloadVideo(entireUrl,title):
# get the id part
part1 = entireUrl.split('http://www.youtube.com/v/',2)[1]
part2 = part1.split('&',1)[0]
# part2='FB9OUcPENL0'
# print(part2)
realLink = "https://www.youtube.com/watch?v="+part2
obj = {"title":title,"link":realLink}
videoLinks.append(obj)
yt = YouTube(realLink)
print yt.get_videos()
fn = yt.filename
yt.set_filename(title)
video = yt.get('mp4')
video.download('videos/')
示例13: getYoutubeUrl
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def getYoutubeUrl(input_url):
if input_url[:32] == "https://www.youtube.com/watch?v=":
yt = YouTube(input_url) # additional sanitization needed
uid = input_url[32:]
elif input_url[:31] == "http://www.youtube.com/watch?v=":
yt = YouTube(input_url) # additional sanitization needed
uid = input_url[31:]
else:
yt = YouTube("https://www.youtube.com/watch?v=%s" % input_url)
yt.set_filename("intro-%s" % input_url)
video = yt.get('mp4', '360p')
return video.url
示例14: extract_files
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def extract_files(url, max_frame=90, skip_time=2):
videoFolder = './server/videos'
if "server" not in os.listdir("."):
os.mkdir("server")
os.mkdir("server/videos")
else:
if "videos" not in os.listdir("server"):
os.mkdir("server/videos")
if "frames" not in os.listdir(videoFolder):
os.mkdir("./server/videos/frames")
# Set filename to id
yt = YouTube(url)
video_id = get_youtube_id(url)
yt.set_filename(video_id)
# download video of certain quality
video = yt.get('mp4', '360p')
try:
print("downloading videos...")
video.download(videoFolder)
print("done downloading video")
except OSError:
print("didn't need to download video")
frames = []
fname = "%s/%s.mp4" % (videoFolder, str(video_id))
vid = imageio.get_reader(fname, 'ffmpeg')
fps = vid.get_meta_data()['fps']
dur = int(math.floor(vid.get_meta_data()['duration']))
i = 0
print("saving frames...")
index = 0
frameFolder = "./server/videos/frames/{0}".format(video_id)
if video_id not in os.listdir("./server/videos/frames/"):
os.mkdir(frameFolder)
while i < dur:
frame = vid.get_data(int(math.floor(i * fps)))
img = Image.fromarray(frame, 'RGB')
img_destination = frameFolder + "/frame-" + str(index) + ".jpg"
img.save(img_destination)
frames.append((frame, i, img_destination))
i += skip_time
index += 1
if index >= max_frame:
break
print("done saving frames.")
vid.close()
return frames, frameFolder
示例15: callback
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import set_filename [as 别名]
def callback():
try:
yt = YouTube(videoLink.get())
try:
yt.set_filename(videoName.get())
except:
os.system("say could not get file name")
try:
video = yt.get(videoType.get(),videoQuality.get())
except:
os.system("say Could not find proprt video quality")
try:
video.download(desktopPath)
except:
os.system("say Could not get donwload path")
except:
os.system("say Invaid link")