当前位置: 首页>>代码示例>>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;未经允许,请勿转载。