本文整理汇总了Python中pytube.YouTube.get方法的典型用法代码示例。如果您正苦于以下问题:Python YouTube.get方法的具体用法?Python YouTube.get怎么用?Python YouTube.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytube.YouTube
的用法示例。
在下文中一共展示了YouTube.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: down
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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)
示例2: __init__
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
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")
示例3: downloadFisicalFile
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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")
示例4: TestYouTube
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
class TestYouTube(unittest.TestCase):
'''Test all methods of Youtube class'''
def setUp(self):
'''Set up the all attributes required for a particular video'''
self.url="https://www.youtube.com/watch?v=Ik-RsDGPI5Y"
self.video_id = 'Ik-RsDGPI5Y'
self.filename = 'Pulp Fiction - Dancing Scene'
self.yt = YouTube(self.url)
#: don't hard code, make is universal
self.videos = ['<Video: MPEG-4 Visual (.3gp) - 144p - Simple>',
'<Video: MPEG-4 Visual (.3gp) - 240p - Simple>',
'<Video: Sorenson H.263 (.flv) - 240p - N/A>',
'<Video: H.264 (.mp4) - 360p - Baseline>',
'<Video: H.264 (.mp4) - 720p - High>',
'<Video: VP8 (.webm) - 360p - N/A>']
# using flv since it has only once video
self.flv = '<Video: Sorenson H.263 (.flv) - 240p - N/A>'
def test_url(self):
self.assertEqual(self.yt.url ,self.url)
def test_video_id(self):
self.assertEqual(self.yt.video_id, self.video_id )
def test_filename(self):
self.assertEqual(self.yt.filename, self.filename)
def test_get_videos(self):
self.assertEqual ( map( str, self.yt.get_videos() ), self.videos )
def test_get_video_data(self):
self.assertEqual((self.yt.get_video_data()['args']['loaderUrl']),
self.url)
def test_get_false(self):
with self.assertRaises(MultipleObjectsReturned):
self.yt.get()
def test_get_true(self):
self.assertEqual( str( self.yt.get('flv') ), self.flv )
def test_filter(self):
self.assertEqual( str( self.yt.filter('flv')[0] ), self.flv )
示例5: downloadVideos
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
def downloadVideos(video_url_list):
video = None
folderName = "YouTubePlaylist"
if not os.path.exists(folderName):
os.mkdir(folderName)
for video_url in video_url_list:
try:
yt = YouTube(video_url)
try:
video = yt.get('mp4','720p')
except Exception:
video = yt.get('mp4','360p')
except Exception as e:
pass
video.download(folderName)
示例6: download_videos
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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
示例7: downloadVideo
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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
示例8: download_videoFrom_youtube
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
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)
示例9: download_Video_Audio
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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...")
示例10: post_submit
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
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))
示例11: youtube_download
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
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)
示例12: download_youtube
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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
示例13: doIt
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
def doIt(vlog_url):
try:
y = YouTube(vlog_url)
except:
print "oops"
return
title = y.title.replace(" ","-")
y.set_filename(title)
matches = db.find({'title':title})
if matches.count() > 0:
for i in matches:
if 'compiled_url' in i:
return_url = i['compiled_url']
return return_url
else:
db.insert({"title":title})
if (('%s.mp4'%(title)) not in os.listdir('.')):
y.get('mp4','360p').download('.')
if '%s_compile.avi'%(title) not in os.listdir("."):
clip = VideoFileClip('%s.mp4'%(title))
opencv_clip = cv2.VideoCapture("%s.mp4"%title)
global frames_count
frames_count = int(round(opencv_clip.get(cv2.cv.CV_CAP_PROP_FPS)))
print frames_count
frames = clip.iter_frames()
selected_frames = detect_faces(frames)
groups = cluster(selected_frames, maxgap = 10)
final_clip = compile(groups, clip)
final_clip.write_videofile('%s_compile.avi'%(title), codec='libx264', fps = frames_count)
os.system('python upload_video.py --file="%s" --title="%s" --description="A compilation of the close-ups from Casey\'s vlog - %s" --category="22" --keywords="vlog, compilation, compile, casey, neistat, caseybot" --privacyStatus="public"'%('%s_compile.avi'%title, title, title))
compiled_url = db.find({'title':title})[0]
return compiled_url["compiled_url"]
示例14: get_vids_from_list
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [as 别名]
def get_vids_from_list(vidlist_file, path=None):
if path == None:
path = os.path.dirname(os.path.abspath(__file__))
with open(vidlist_file) as vl:
for video_url in vl:
video_url = video_url.strip()
yt = YouTube(video_url)
video = yt.get('mp4', '720p')
video.download(path)
示例15: download_links
# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get [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