当前位置: 首页>>代码示例>>Python>>正文


Python YouTube.get_videos方法代码示例

本文整理汇总了Python中pytube.YouTube.get_videos方法的典型用法代码示例。如果您正苦于以下问题:Python YouTube.get_videos方法的具体用法?Python YouTube.get_videos怎么用?Python YouTube.get_videos使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytube.YouTube的用法示例。


在下文中一共展示了YouTube.get_videos方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: down

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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)
开发者ID:dovinmu,项目名称:misc,代码行数:29,代码来源:downYoutubeMovie.py

示例2: download_now

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
	def download_now(self, url, codec='mp4', location='/tmp/'):
		try:
			yt = YouTube(url)
			yt.get_videos()
			video = yt.filter(codec)[0]
			print 'file name:', video.filename
			video.download(location, on_progress=utils.print_status)
		except Exception, e:
			print "Error: Invalid URL or network problem or file exist"
开发者ID:samuelsawers,项目名称:buscador,代码行数:11,代码来源:youtube.py

示例3: download_now

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
	def download_now(self, url, codec='mp4', location='/tmp/'):
		try:
			yt = YouTube(self.url)
			yt.get_videos()
			video = yt.filter(codec)[0]
			video.download(location)
		except Exception, e:
			print e
			print "Error: Invalid URL or network problem"
开发者ID:samuelsawers,项目名称:buscador,代码行数:11,代码来源:pytube_test.py

示例4: downloadVideo

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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/')
开发者ID:chelseakwong,项目名称:PresidentialWords,代码行数:17,代码来源:fetchAndForceAlign.py

示例5: fetch_video_by_url

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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
开发者ID:KeluDiao,项目名称:pytube,代码行数:34,代码来源:batch.py

示例6: download_single_video

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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)
开发者ID:polltooh,项目名称:FineGrainedAction,代码行数:27,代码来源:download_video.py

示例7: download_videoFrom_youtube

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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)
开发者ID:avi0gaur,项目名称:Ytube,代码行数:9,代码来源:YtDown.py

示例8: downloadVideo

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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
开发者ID:jsinix,项目名称:codemine,代码行数:33,代码来源:massSecVidDl.py

示例9: download_youtube

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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
开发者ID:pytube,项目名称:antioch,代码行数:58,代码来源:downloader.py

示例10: download_video

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
def download_video(video_url):  # this ffunction will take video url as input and download the corresponding video
    yt = YouTube(video_url)
    print("The available formats and quality of %s are as follows :" % yt.filename)
    pprint(yt.get_videos())
    vid_for = input("Please select appropriate file format and quality (e.g. flv 480p) : ")
    print("The download of %s in " % yt.filename + vid_for + " quality is starting")
    vid_for = vid_for.split(" ")
    video = yt.get(vid_for[0], resolution=vid_for[1])
    video.download("")
    print("Download Competed")
开发者ID:DefCon-007,项目名称:Project-Youtube,代码行数:12,代码来源:YouTube_Search.py

示例11: fetch_video_qualtiy

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
def fetch_video_qualtiy(url):
    """
    Fetch a list of available video qualities.

    :param url: Url to fetch available video options.
    :type url: :class:`str`
    :returns: Iterable of available video options.
    :rtype: Iterable of :class:`str`
    """
    youtube = YouTube(url)
    for element in youtube.get_videos():
        yield element
开发者ID:iampriyavarshney,项目名称:Hobby,代码行数:14,代码来源:tube.py

示例12: TestYouTube

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [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 )
开发者ID:garg10may,项目名称:pytube,代码行数:52,代码来源:test.py

示例13: test_download_video

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
    def test_download_video(self):
        video_id = 'cr04UelmPqg'  # https://www.youtube.com/watch?v=cr04UelmPqg
        video_info_url_base = 'https://www.youtube.com/watch?v=%s'
        video_url = video_info_url_base % video_id
        youtube = YouTube(video_url)

        video = youtube.get_videos()[0]  # get_best_video(youtube)

        self.assertEqual('3gp', video.extension)

        current_folder = os.path.dirname(os.path.realpath(__file__))
        file_path = os.path.join(current_folder, 'rabbit_youtube_test.%s' % video.extension)
        video.download(file_path)
        self.assertTrue(os.path.isfile(file_path))
        os.remove(file_path)
开发者ID:guoliang-dev,项目名称:rabbit-youtube,代码行数:17,代码来源:test_youtube_api.py

示例14: run

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
def run():

    for concert in Concert.objects.all():
        artists = ', '.join([a.name for a in concert.artists.all()])

        print '{} - {} @ {} on {}'.format(concert.id,artists,concert.venue.name,concert.date)


    concert_id = int(raw_input('Please enter a concert ID: '))

    concert = Concert.objects.get(pk=concert_id)


    youtube_url = None
    videos = []

    while youtube_url != "":
        youtube_url = raw_input('Paste a YouTube URL (or press ENTER to finish): ')

        if youtube_url != "":
            yt = YouTube(youtube_url)

            print 'Please select one of the following:'

            dees_videos = yt.get_videos()

            for (index, video) in enumerate(dees_videos):
                print '{}.) {} @ {}'.format(index, video.extension, video.resolution)

            index = int(raw_input('Which one?: '))

            video = dees_videos[index]

            videos.append(video)


    print 'Ready to upload {} videos to concert {}'.format(len(videos), concert_id)

    confirm = raw_input('Are you sure (Y/N): ')

    if confirm.lower() != 'y':
        sys.exit(1)

    # for video in videos:

    print "\n\n\nUPLOAD JAWNS COMPLETE :D"
开发者ID:projectjamjar,项目名称:masonjar,代码行数:48,代码来源:youtube_to_jamjar.py

示例15: Dyou

# 需要导入模块: from pytube import YouTube [as 别名]
# 或者: from pytube.YouTube import get_videos [as 别名]
def Dyou():
	link = input("URL: ")
	if not "https://" in link:
		link = "https://"+link
	else:
		link = link
	try:
		urllib.request.urlopen(link)
		
		url = YouTube(link)
		print("\n\033[36mNome\033[0;0m: \n\033[31m", url.filename, "\033[0;0m")
		print("\033[36mformatos:\033[0;0m")
		pprint(url.get_videos())

		try:
			formato = input("Formato: exemplo: \033[31mmp4\033[0;0m\n")
			resolucao = input("Resolução: exemplo: \033[31m720p\033[0;0m\n")
			print ("Você escolheu :\033[36m", formato+", "+resolucao, "\033[0;0m")
			video = url.get(formato, resolucao)
			print("[Baixando...!]")
			
			if sys.platform == "linux":
				try:
					video.download("/tmp/")
					print("[Download concluido]")
				except OSError:
					print("Arquivo já existente!")
			
			elif sys.platform == "win32":
				try:
					video.download("/temp/")
					print("[Download concluido]")
				except OSError:
					print("Arquivo já existente!")
			
			else:
				print("[ERRO!?]")
		
		except pytube.exceptions.DoesNotExist:
			print("Formato não valido!")

	except (urllib.error.HTTPError, urllib.error.URLError, urllib.error.ContentTooShortError):
		print(link, "\nNome: \n\033[31m[Não válido]\033[0;0m")
开发者ID:luiseduardosilva,项目名称:python,代码行数:45,代码来源:Dyou.py


注:本文中的pytube.YouTube.get_videos方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。