當前位置: 首頁>>代碼示例>>Python>>正文


Python youtube_dl.YoutubeDL方法代碼示例

本文整理匯總了Python中youtube_dl.YoutubeDL方法的典型用法代碼示例。如果您正苦於以下問題:Python youtube_dl.YoutubeDL方法的具體用法?Python youtube_dl.YoutubeDL怎麽用?Python youtube_dl.YoutubeDL使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在youtube_dl的用法示例。


在下文中一共展示了youtube_dl.YoutubeDL方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: download_clip

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download_clip(url, name):
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': dir_utils.get_perm_med_dir() + f'/sound_board/{name}.wav',
        'noplaylist': True,
        'continue_dl': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
            'preferredquality': '192', }]
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.cache.remove()
            info_dict = ydl.extract_info(url, download=False)
            ydl.prepare_filename(info_dict)
            ydl.download([url])
            return True
    except Exception:
        return False 
開發者ID:DuckBoss,項目名稱:JJMumbleBot,代碼行數:22,代碼來源:sound_board_utility.py

示例2: extract_video_highres

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def extract_video_highres(self):
        if not YoutubeDL:
            raise ModuleNotFoundError(
                "youtube-dl must be installed to download videos in high resolution."
            )
        ydl_opts = {
            'format': 'best',
            'quiet': True,
        }
        try:
            post_id = self.post.get('post_id')
            video_page = 'https://www.facebook.com/' + post_id
            with YoutubeDL(ydl_opts) as ydl:
                url = ydl.extract_info(video_page, download=False)['url']
                return {'video': url}
        except ExtractorError as ex:
            logger.error("Error extracting video with youtube-dl: %r", ex)
        return None 
開發者ID:kevinzg,項目名稱:facebook-scraper,代碼行數:20,代碼來源:extractors.py

示例3: download_song_name

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download_song_name(url):
    try:
        with youtube_dl.YoutubeDL(YoutubeHelper.ydl_opts) as ydl:
            ydl.cache.remove()
            info_dict = ydl.extract_info(url, download=True)
            if info_dict['duration'] >= YoutubeHelper.max_track_duration:
                return None
            if info_dict['duration'] <= 0.1:
                return None

            prep_struct = {
                'std_url': url,
                'main_url': info_dict['url'],
                'main_title': info_dict['title'],
                'img_id': info_dict['id'],
                'duration': info_dict['duration']
            }
            return prep_struct
    except youtube_dl.utils.DownloadError:
        return None 
開發者ID:DuckBoss,項目名稱:JJMumbleBot,代碼行數:22,代碼來源:youtube_helper.py

示例4: download_next

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download_next():
    queue_list = list(YoutubeHelper.queue_instance.queue_storage)
    if len(queue_list) > 0:
        youtube_url = queue_list[-1]['std_url']
    else:
        return
    if os.path.exists(f"{dir_utils.get_temp_med_dir()}/youtube/{queue_list[-1]['img_id']}.jpg"):
        dprint(f"Thumbnail exists for {queue_list[-1]['img_id']}.jpg...skipping")
        return
    try:
        with youtube_dl.YoutubeDL(YoutubeHelper.ydl_opts) as ydl:
            ydl.cache.remove()
            ydl.extract_info(youtube_url, download=True)
    except youtube_dl.utils.DownloadError as e:
        dprint(e)
        return
    return 
開發者ID:DuckBoss,項目名稱:JJMumbleBot,代碼行數:19,代碼來源:youtube_helper.py

示例5: setUp

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def setUp(self):
        super().setUp()

        try:
            # try to find out whether youtube is happy with us this time
            # send a request and skip the test if there is an error
            ydl_opts = Youtube.get_ydl_opts()
            ydl_opts["logger"] = YoutubeDLLogger(self)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                self.info_dict = ydl.download(
                    ["https://www.youtube.com/watch?v=wobbf3lb2nk"]
                )
        except (youtube_dl.utils.ExtractorError, youtube_dl.utils.DownloadError) as e:
            self.skipTest(f"Error when interacting with youtube, skipping test: {e}")

        # reduce the number for youtube playlists
        self.client.post(reverse("set_max_playlist_items"), {"value": "3"})

        # clear test cache; ensure that it's the test directory
        if os.path.split(os.path.dirname(settings.SONGS_CACHE_DIR))[1] == "test_cache":
            for member in os.listdir(settings.SONGS_CACHE_DIR):
                member_path = os.path.join(settings.SONGS_CACHE_DIR, member)
                if os.path.isfile(member_path):
                    os.remove(member_path) 
開發者ID:raveberry,項目名稱:raveberry,代碼行數:26,代碼來源:test_youtube.py

示例6: check_available

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def check_available(self) -> bool:
        try:
            with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:
                self.info_dict = ydl.extract_info(self.query, download=False)
        except (youtube_dl.utils.ExtractorError, youtube_dl.utils.DownloadError) as e:
            self.error = e
            return False

        # this value is not an exact match, but it's a good approximation
        if "entries" in self.info_dict:
            self.info_dict = self.info_dict["entries"][0]

        self.id = self.info_dict["id"]

        size = self.info_dict["filesize"]
        max_size = self.musiq.base.settings.basic.max_download_size * 1024 * 1024
        if (
            max_size != 0
            and self.check_cached() is None
            and (size is not None and size > max_size)
        ):
            self.error = "Song too long"
            return False
        return True 
開發者ID:raveberry,項目名稱:raveberry,代碼行數:26,代碼來源:youtube.py

示例7: return_youtubevideo_params

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def return_youtubevideo_params(url):
    """
	returns Youtube Video parameters(FPS, dimensions) directly using Youtube-dl
	"""
    ydl = youtube_dl.YoutubeDL(
        {
            "outtmpl": "%(id)s%(ext)s",
            "noplaylist": True,
            "quiet": True,
            "format": "bestvideo",
        }
    )
    with ydl:
        result = ydl.extract_info(
            url, download=False
        )  # We just want to extract the info
    return (int(result["width"]), int(result["height"]), float(result["fps"])) 
開發者ID:abhiTronix,項目名稱:vidgear,代碼行數:19,代碼來源:test_camgear.py

示例8: download_song

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download_song(song_url, song_title):
    """
    Download a song using youtube url and song title
    """

    outtmpl = song_title + '.%(ext)s'
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': outtmpl,
        'postprocessors': [
            {'key': 'FFmpegExtractAudio','preferredcodec': 'mp3',
             'preferredquality': '192',
            },
            {'key': 'FFmpegMetadata'},
        ],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(song_url, download=True) 
開發者ID:kalbhor,項目名稱:MusicTools,代碼行數:21,代碼來源:musictools.py

示例9: download

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download(self):
        ydl_options = self._prepare_ytd_options()
        with youtube_dl.YoutubeDL(ydl_options) as ydl:
            ydl.add_default_info_extractors()
            ydl.add_progress_hook(self.hook)
            try:
                ydl.download([self.url])
            except (
                    youtube_dl.utils.DownloadError,
                    youtube_dl.utils.ContentTooShortError,
                    youtube_dl.utils.ExtractorError,
                    youtube_dl.utils.UnavailableVideoError
            ) as e:
                self.error_occurred = True
                self.remove_row_signal.emit()
                self.remove_url_signal.emit(self.url)
                self.status_bar_signal.emit(str(e)) 
開發者ID:yasoob,項目名稱:youtube-dl-GUI,代碼行數:19,代碼來源:Download.py

示例10: download_song

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def download_song(song_url, song_title):
    '''
    Downloads song from youtube-dl
    '''
    outtmpl = song_title + '.%(ext)s'
    ydl_opts = {
        'format': 'bestaudio/best',
        'outtmpl': outtmpl,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        },
            {'key': 'FFmpegMetadata'},
        ],

    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(song_url, download=True) 
開發者ID:kalbhor,項目名稱:MusicNow,代碼行數:22,代碼來源:command_line.py

示例11: list_formats

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def list_formats(info_dict: dict) -> str:
    """YoutubeDL's list_formats method but without format notes.

    Args:
        info_dict (``dict``):
            Dictionary which is returned by YoutubeDL's extract_info method.

    Returns:
        ``str``:
            All available formats in order as a string instead of stdout.
    """
    formats = info_dict.get('formats', [info_dict])
    table = [
        [f['format_id'], f['ext'], youtube_dl.YoutubeDL.format_resolution(f)]
        for f in formats
        if f.get('preference') is None or f['preference'] >= -1000]
    if len(formats) > 1:
        table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'

    header_line = ['format code', 'extension', 'resolution']
    fmtStr = (
        '`Available formats for %s:`\n`%s`' %
        (info_dict['title'], youtube_dl.render_table(header_line, table))
    )
    return fmtStr 
開發者ID:TG-UserBot,項目名稱:TG-UserBot,代碼行數:27,代碼來源:yt_dl.py

示例12: shouldUseYoutubeDl

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def shouldUseYoutubeDl(url):
    for siteMask in youtubeDlSitesSupported:
        if siteMask in url:
            isBlacklisted = False
            for blacklistSite in youtubeDlBlacklistSites:
                if blacklistSite in url:
                    isBlacklisted = True
                    break

            # Use the gfycat api for these, if available
            # Ever since the creation of RedGifs, use YoutubeDL for all gfycat links...
            # if settings.settings['Gfycat_Client_id'] and 'gfycat.com' in url:
                # isBlacklisted = True

            if isBlacklisted:
                # We probably have another downloader
                return False

            # YoutubeDL should support this site
            return True

    return False

# Returns (success or failure, output file or failure message) 
開發者ID:makuto,項目名稱:Liked-Saved-Image-Downloader,代碼行數:26,代碼來源:videoDownloader.py

示例13: __init__

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def __init__(self, requester, item_info):
        """
        :param requester: The user that queued the item.
        :type requester: discord.Member
        :param item_info: Document containing the queued item's details.
        :type item_info: dict
        """
        self.requester = requester
        self.item_info = item_info
        self.url = self.item_info.get('webpage_url')
        self.video_id = self.item_info.get('id', self.url)
        self.uploader = self.item_info.get('uploader', 'Unknown')
        self.title = self.item_info.get('title')
        self.thumbnail = self.item_info.get('thumbnail', 'https://i.imgur.com/CGPNJDT.png')
        self.duration = int(self.item_info.get('duration', 0))
        self.downloaded = False
        self.loop = asyncio.get_event_loop()
        self.threads = ThreadPoolExecutor()
        self.ytdl_params = ytdl_params
        self.ytdl = youtube_dl.YoutubeDL(self.ytdl_params)
        self.token = self.tokenize()
        self.location = None 
開發者ID:lu-ci,項目名稱:apex-sigma-core,代碼行數:24,代碼來源:music.py

示例14: _get_info_from_url

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def _get_info_from_url(self):
        self.log.info("url: fetching metadata of url %s " % self.url)
        ydl_opts = {
            'noplaylist': True
        }
        succeed = False
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            attempts = var.config.getint('bot', 'download_attempts', fallback=2)
            for i in range(attempts):
                try:
                    info = ydl.extract_info(self.url, download=False)
                    self.duration = info['duration']
                    self.title = info['title']
                    self.keywords = info['title']
                    succeed = True
                    return True
                except youtube_dl.utils.DownloadError:
                    pass
                except KeyError:  # info has no 'duration'
                    break

        if not succeed:
            self.ready = 'failed'
            self.log.error("url: error while fetching info from the URL")
            raise ValidationFailedError(constants.strings('unable_download', item=self.format_title())) 
開發者ID:azlux,項目名稱:botamusique,代碼行數:27,代碼來源:url.py

示例15: videoDownloader

# 需要導入模塊: import youtube_dl [as 別名]
# 或者: from youtube_dl import YoutubeDL [as 別名]
def videoDownloader(string, passedTitle, yearVar):
  # Options for the video downloader
  ydl1_opts = {
    'outtmpl': os.path.join(TheaterTrailersHome, 'Trailers', '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1}).mp4'.format(passedTitle, yearVar)),
    'ignoreerrors': True,
    'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
  }
  with youtube_dl.YoutubeDL(ydl1_opts) as ydl:
    logger.info("downloading {0} from {1}".format(passedTitle, string))
    ydl.download([string])
    shutil.copy2(
        os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1}).mp4'.format(passedTitle, yearVar)),
        os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar), '{0} ({1})-trailer.mp4'.format(passedTitle, yearVar))
      )
    shutil.copy2(
        os.path.join(TheaterTrailersHome, 'res', 'poster.jpg'),
        os.path.join(trailerLocation, '{0} ({1})'.format(passedTitle, yearVar))
      )
    updatePlex()


# Downloads info for the videos from the playlist 
開發者ID:Electronickss,項目名稱:TheaterTrailers,代碼行數:24,代碼來源:theaterTrailers.py


注:本文中的youtube_dl.YoutubeDL方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。