本文整理汇总了Python中pytube.YouTube类的典型用法代码示例。如果您正苦于以下问题:Python YouTube类的具体用法?Python YouTube怎么用?Python YouTube使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了YouTube类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: downloadVideo
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
示例2: fetch_video_by_url
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
示例3: yt_api
def yt_api(yt_id):
video = YouTube()
try:
video.url = "http://youtube.com/watch?v=%s" % yt_id
except:
return render_template('404.html'), 404
return json.dumps({"%s-%s" % (video.resolution, video.extension) : video.url for video in video.videos})
示例4: download_Video_Audio
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...")
示例5: download_videos
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
示例6: yt_web
def yt_web(yt_id):
video = YouTube()
try:
video.url = "http://youtube.com/watch?v=%s" % yt_id
except:
return render_template('404.html'), 404
return render_template("webtable.html", videos=[("%s-%s" % (video.resolution, video.extension) , video.url) for video in video.videos])
示例7: downloadSong
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"
示例8: get_song_info
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
示例9: _download_file
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
示例10: download_videoFrom_youtube
def download_videoFrom_youtube(url, savePath):
yt = YouTube(url)
pprint(yt.get_videos())
print(yt.filename)
#yt.set_filename()
video = yt.get('mp4', '360p')
video.download(savePath)
示例11: download_single_video
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)
示例12: _download_file
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)
video = yt.filter('mp4')[0]
video.download(file_path)
return file_path
示例13: __init__
def __init__(self,url):
self.url = url
yt = YouTube()
yt.url = url
video = yt.get('mp4', '480p')
video = yt.get('mp4')
video.download()
self.name = (str(yt.filename) + ".mp4")
示例14: post_submit
def post_submit():
yt = YouTube()
url = request.form.get('url')
yt.url = url
video = yt.get('mp4', '360p')
video.download('./')
filename = yt.filename
return redirect(url_for('index', filename=filename))
示例15: youtube_download
def youtube_download(video_ids):
video_ids = video_ids.split('\n')
for video_id in video_ids:
yt = YouTube('https://www.youtube.com/watch?v=' + video_id)
video = yt.get('mp4')
name = yt.filename
if not os.path.isfile('res/' + name + 'mp4'):
video.download('res/')
yield ('res/' + name + '.mp4', name)