视频下载软件 yt-dlp 的使用教程

USAGE AND OPTIONS

yt-dlp [OPTIONS] [--] URL [URL...]

Ctrl+F is your friend :D

General Options

没有常用的

网络 Network Options:

--proxy URL                     使用代理
                                Use the specified HTTP/HTTPS/SOCKS proxy. To
                                enable SOCKS proxy, specify a proper scheme,
                                e.g. socks5://user:pass@127.0.0.1:1080/.
                                Pass in an empty string (--proxy "") for
                                direct connection
...

Geo-restriction

没有常用的

视频筛选 Video Selection

...
--min-filesize SIZE             Abort download if filesize is smaller than
                                SIZE, e.g. 50k or 44.6M
--max-filesize SIZE             Abort download if filesize is larger than
                                SIZE, e.g. 50k or 44.6M
...
--no-playlist                   仅下载视频而非整个列表
                                Download only the video, if the URL refers
                                to a video and a playlist
--yes-playlist                  下载整个列表
                                Download the playlist, if the URL refers to
                                a video and a playlist
...

下载选项 Download Options

没有常用的

Filesystem Options

...

-P, --paths [TYPES:]PATH        The paths where the files should be
                                downloaded. Specify the type of file and the
                                path separated by a colon ":". All the same
                                TYPES as --output are supported.
                                Additionally, you can also provide "home"
                                (default) and "temp" paths. All intermediary
                                files are first downloaded to the temp path
                                and then the final files are moved over to
                                the home path after download is finished.
                                This option is ignored if --output is an
                                absolute path
-o, --output [TYPES:]TEMPLATE   Output filename template; see "OUTPUT
                                TEMPLATE" for details
--output-na-placeholder TEXT    Placeholder for unavailable fields in
                                --output (default: "NA")

...

-w, --no-overwrites             Do not overwrite any files
--force-overwrites              Overwrite all video and metadata files. This
                                option includes --no-continue
--no-force-overwrites           Do not overwrite the video, but overwrite
                                related files (default)
-c, --continue                  Resume partially downloaded files/fragments
                                (default)
--no-continue                   Do not resume partially downloaded
                                fragments. If the file is not fragmented,
                                restart download of the entire file
--part                          Use .part files instead of writing directly
                                into output file (default)
--no-part                       Do not use .part files - write directly into
                                output file
--mtime                         Use the Last-modified header to set the file
                                modification time (default)
--no-mtime                      Do not use the Last-modified header to set
                                the file modification time

...

--cookies FILE                  Netscape formatted file to read cookies from
                                and dump cookie jar in

...

缩略图 Thumbnail Options

--write-thumbnail               Write thumbnail image to disk
--no-write-thumbnail            Do not write thumbnail image to disk (default)
--write-all-thumbnails          Write all thumbnail image formats to disk
--list-thumbnails               List available thumbnails of each video.
                                Simulate unless --no-simulate is used

Internet Shortcut Options

没有常用的

Verbosity and Simulation Options

-q, --quiet                     Activate quiet mode. If used with --verbose,
                                print the log to stderr
--no-quiet                      Deactivate quiet mode. (Default)
--no-warnings                   Ignore warnings

...

--skip-download                 Do not download the video but write all
                                related files (Alias: --no-download)
-O, --print [WHEN:]TEMPLATE     Field name or output template to print to
                                screen, optionally prefixed with when to
                                print it, separated by a ":". Supported
                                values of "WHEN" are the same as that of
                                --use-postprocessor (default: video).
                                Implies --quiet. Implies --simulate unless
                                --no-simulate or later stages of WHEN are
                                used. This option can be used multiple times

...

--no-progress                   Do not print progress bar
--progress                      Show progress bar, even if in quiet mode
--console-title                 Display progress in console titlebar
--progress-template [TYPES:]TEMPLATE
                                Template for progress outputs, optionally
                                prefixed with one of "download:" (default),
                                "download-title:" (the console title),
                                "postprocess:",  or "postprocess-title:".
                                The video's fields are accessible under the
                                "info" key and the progress attributes are
                                accessible under "progress" key. E.g.
                                --console-title --progress-template
                                "download-title:%(info.id)s-%(progress.eta)s"
--progress-delta SECONDS        Time between progress output (default: 0)

...

Workarounds

没有常用的

Video Format Options

-f, --format FORMAT             Video format code, see "FORMAT SELECTION"
                                for more details

...

-F, --list-formats              List available formats of each video.
                                Simulate unless --no-simulate is used

...

字幕 Subtitle Options

--write-subs                    Write subtitle file
--no-write-subs                 Do not write subtitle file (default)
--write-auto-subs               Write automatically generated subtitle file
                                (Alias: --write-automatic-subs)
--no-write-auto-subs            Do not write auto-generated subtitles
                                (default) (Alias: --no-write-automatic-subs)
--list-subs                     List available subtitles of each video.
                                Simulate unless --no-simulate is used
--sub-format FORMAT             Subtitle format; accepts formats preference,
                                e.g. "srt" or "ass/srt/best"
--sub-langs LANGS               Languages of the subtitles to download (can
                                be regex) or "all" separated by commas, e.g.
                                --sub-langs "en.*,ja". You can prefix the
                                language code with a "-" to exclude it from
                                the requested languages, e.g. --sub-langs
                                all,-live_chat. Use --list-subs for a list
                                of available language tags

Authentication Options

没有常用的

后加工 Options:

-x, --extract-audio             转换成纯音频文件
                                (requires ffmpeg and ffprobe)
--audio-format FORMAT           转换的音频格式当使用 `-x` 参数时
                                (currently supported: best (default),
                                aac, alac, flac, m4a, mp3, opus, vorbis,
                                wav). You can specify multiple rules using
                                similar syntax as --remux-video

...

SponsorBlock Options

没有常用的

Extractor Options

没有常用的

配置

您可以通过在配置文件中放置任何支持的命令行选项来配置 yt-dlp。配置从以下位置加载:

  1. Main Configuration:
    • The file given to --config-location
  2. 便携式配置(建议用于便携式安装) :
    • 如果使用二进制文件,则在与二进制文件相同的目录下使用 yt-dlp.conf
    • 如果从源代码运行,yt_dlp 的父目录中的 yt-dlp.conf
  3. Home Configuration:
    • yt-dlp.conf in the home path given to -P
    • If -P is not given, the current directory is searched
  4. User Configuration:
    • ${XDG_CONFIG_HOME}/yt-dlp.conf
    • ${XDG_CONFIG_HOME}/yt-dlp/config (recommended on Linux/macOS)
    • ${XDG_CONFIG_HOME}/yt-dlp/config.txt
    • ${APPDATA}/yt-dlp.conf
    • ${APPDATA}/yt-dlp/config (recommended on Windows)
    • ${APPDATA}/yt-dlp/config.txt
    • ~/yt-dlp.conf
    • ~/yt-dlp.conf.txt
    • ~/.yt-dlp/config
    • ~/.yt-dlp/config.txt
  5. System Configuration:
    • /etc/yt-dlp.conf
    • /etc/yt-dlp/config
    • /etc/yt-dlp/config.txt

E.g. with the following configuration file, yt-dlp will always extract the audio, not copy the mtime, use a proxy and save all videos under YouTube directory in your home directory:

# Lines starting with # are comments

# Always extract audio
-x

# Do not copy the mtime
--no-mtime

# Use this proxy
--proxy 127.0.0.1:3128

# Save all videos under YouTube directory in your home directory
-o ~/YouTube/%(title)s.%(ext)s

注意: 配置文件中的选项与常规命令行调用中使用的选项相同; 因此,在 -—— 之后必须没有空格,例如 -o——proxy,而不是 - o—— proxy。 必要时还必须将它们加引号,就好像它是 UNIX shell 一样。

如果您想禁用特定的 yt-dlp 运行的所有配置文件,可以使用 ——ignore-config。 如果在配置文件中找到 ——ignore-config,则不会加载进一步的配置。 例如,在便携式配置文件中使用该选项可以防止加载 Home Configuration、User Configuration 和 System Configuration。 此外,(为了向后兼容)如果在 System Configuration 中找到 ——ignore-config,则不会加载 User Configuration。

Configuration file encoding

没有做翻译, 需要的话看原文

Authentication with netrc

没有做翻译, 需要的话看原文

OUTPUT TEMPLATE

-o 选项用于指定输出文件名的模板,而 -P 选项用于指定每种类型的文件应该保存到的路径。

-o 最简单的用法是在下载单个文件时不设置任何模板参数,就像在 yt-dlp -o funny_video.flv "https://some/video" 中一样(不推荐这样的硬编码文件扩展名,可能会破坏一些 post-processing)。

它也可能包含在下载每个视频时将被替换的特殊序列。特殊序列可以根据 Python 字符串格式化操作进行格式化,例如 %(NAME)s%(NAME)05d。 澄清一下,这是一个百分比符号,后跟括号中的名称,然后是格式化操作。

字段名本身(括号内的部分)也可以有一些特殊的格式:

  1. 遍历对象: 元数据中可用的字典和列表可以通过使用点 . 来遍历, 比如 %(tags.0)s, %(subtitles.en.-1.ext)s。你可以用 : 来做 Python 切片, 比如 %(id.3:7)s, %(id.6:2:-1)s, %(formats.:.format_id)s。大括号 {} 可以用来构建只包含特定键的字典, 比如 %(formats.:.{format_id,height})#j。空字段名 %()s 指的是整个信息表, 比如 %(.{id,title})s。请注意,下面没有列出使用此方法可用的所有字段。 使用 -j 查看这些字段。

  2. 算术(Arithmetic): 可以使用 +, -* 对数字字段进行简单的算术运算, 比如 %(playlist_index+10)03d, %(n_entries+1-playlist_index)d

  3. 日期/时间格式化(Date/time Formatting): 日期/时间字段可以根据 strftime 格式进行格式化,通过使用 > 将其与字段名称分开来指定, 比如 %(duration>%H-%M-%S)s, %(upload_date>%Y-%m-%d)s, %(epoch-3600>%H-%M-%S)s

  4. 备选(Alternatives): 备选字段可以用 , 来分隔, 比如 %(release_date>%Y,upload_date>%Y|Unknown)s

  5. 替换(Replacement): 可以根据 str.format mini-language 使用 & 分隔符指定替换值。如果字段不为空,则将使用此替换值代替实际字段内容。这是在考虑替代字段之后完成的(This is done after alternate fields are considered),因此,如果任何可选字段不为空,则使用替换, 比如 %(chapters&has chapters|no chapters)s, %(title&TITLE={:>20}|NO TITLE)s

  6. 默认: 当字段为空时,可以使用 | 分隔符指定文本默认值。这将覆盖 --output-na-placeholder 选项, 比如 %(uploader|Unknown)s

  7. More Conversions: 除了正常的格式类型 diouxXeEfFgGcrs, yt-dlp 另外支持转换为 B = Bytes, j = json(flag # 用于优美打印, + 用于 Unicode), h = HTML 转义, l = 一个逗号分隔列表(flag # 用作 \n 换行分隔), q = 一个字符串引用的终端(flag # 用于分割一个列表为参数列表), D = 增加小数后缀(例如 10M)(flag # 使用 1024 作为 factor), S = Sanitize as filename (flag # for restricted)

  8. Unicode normalization: The format type U can be used for NFC Unicode normalization. The alternate form flag (#) changes the normalization to NFD and the conversion flag + can be used for NFKC/NFKD compatibility equivalence normalization. E.g. %(title)+.100U is NFKC

总而言之,字段名的一般语法是:

%(name[.keys][addition][>strf][,alternate][&replacement][|default])[flags][width][.precision][length]type

Additionally, you can set different output templates for the various metadata files separately from the general output template by specifying the type of file followed by the template separated by a colon :. The different file types supported are subtitle, thumbnail, description, annotation (deprecated), infojson, link, pl_thumbnail, pl_description, pl_infojson, chapter, pl_video. E.g. -o "%(title)s.%(ext)s" -o "thumbnail:%(title)s\%(title)s.%(ext)s" will put the thumbnails in a folder with the same name as the video. If any of the templates is empty, that type of file will not be written. E.g. --write-thumbnail -o "thumbnail:" will write thumbnails only for playlists and not for video.

此外, 可以为各种元数据文件设置不同的输出模板(output templates), 方法是指定文件类型, 后面跟以 : 分隔的模板。不同的文件类型支持的模板有 subtitle(字幕), thumbnail(缩略图), description(描述), annotation (注释, 已废弃), infojson(信息 JSON), link(链接), pl_thumbnail(播放列表缩略图), pl_description, pl_infojson, chapter, pl_video, 例如: -o "%(title)s.%(ext)s" -o "thumbnail:%(title)s\%(title)s.%(ext)s" 会把缩略图放在与视频同名的文件夹中。如果模板为空,则不会写入该类型的文件, 比如 --write-thumbnail -o "thumbnail:" 将只为播放列表列表写缩略图, 而不是单一视频

注意: 由于 post-processing(即合并等),实际输出文件名可能会有所不同。在所有 post-processing 完成后,使用 --print after_move:filepath 来获取名称。

可用的字段有:

name data_type desc
id string 视频🆔
title string 视频标题
fulltitle string 视频标题(忽略实时时间戳和通用标题)
ext string 视频文件扩展名
alt_title string 视频二级标题
description string 视频描述
display_id string 视频的替代标识符
uploader string 视频上传者的全名
uploader_id string 视频上传者的昵称或🆔
uploader_url string 视频上传者个人资料的 URL
license string 视频被授权使用的许可名称
creators list 视频的创作者
creator string 视频的创作者; 逗号分隔
timestamp numeric 视频可用时的 UNIX 时间戳
upload_date string 视频上传的 UTC 日期 (YYYYMMDD)
release_timestamp numeric 视频发布时的 UNIX 时间戳
release_date string 视频发布的 UTC 日期 (YYYYMMDD)
release_year numeric 视频或专辑发行的年份(YYYY)
modified_timestamp numeric 视频最后修改时刻的 UNIX 时间戳
modified_date string The date (YYYYMMDD) when the video was last modified in UTC
channel string 上传视频的频道全名
channel_id string 频道🆔
channel_url string 频道 URL
channel_follower_count numeric 频道粉丝数
channel_is_verified boolean 频道是否在平台上被认证
location string 视频拍摄的实际地点
duration numeric 视频时长,以秒为单位
duration_string string 视频时长 (HH:mm:ss)
view_count numeric 有多少用户在该平台上观看了该视频
concurrent_view_count numeric 目前有多少用户在平台上观看视频
like_count numeric 视频的点赞数
dislike_count numeric 视频的点踩数
repost_count numeric 视频被转发的次数
average_rating numeric 用户给出的平均评分,使用的尺度取决于网页
comment_count numeric 视频上的评论数(对于某些提取器,评论只在最后下载,因此此字段不能使用)
age_limit numeric 观看视频的年龄限制(岁)
live_status string One of “not_live”, “is_live”, “is_upcoming”, “was_live”, “post_live” (was live, but VOD is not yet processed)
is_live boolean 这个视频是直播还是固定长度的视频
was_live boolean 这段视频最初是否为直播
playable_in_embed string 是否允许该视频在其他网站的嵌入式播放器中播放
availability string Whether the video is “private”, “premium_only”, “subscriber_only”, “needs_auth”, “unlisted” or “public”
media_type string 根据网站分类的媒体类型, e.g. “episode”, “clip”, “trailer”
start_time numeric Time in seconds where the reproduction(复制) should start, as specified in the URL
end_time numeric Time in seconds where the reproduction(复制) should end, as specified in the URL
extractor string 提取器名称(通常是视频平台的名称)
extractor_key string 提取器的密钥名
epoch numeric Unix epoch of when the information extraction was completed
autonumber numeric 每次下载时增加的数字, starting at --autonumber-start, padded with leading zeros to 5 digits
video_autonumber numeric Number that will be increased with each video
n_entries numeric 在播放列表中提取的项目总数
playlist_id string 包含该视频的播放列表🆔
playlist_title string 包含该视频的播放列表名
playlist string playlist_title if available or else playlist_id
playlist_count numeric Total number of items in the playlist. May not be known if entire playlist is not extracted; 播放列表中的项目总数。可能不知道,如果整个播放列表没有提取
playlist_index numeric 播放列表中视频的索引 padded with leading zeros according the final index
playlist_autonumber numeric Position of the video in the playlist download queue padded with leading zeros according to the total length of the playlist
playlist_uploader string Full name of the playlist uploader
playlist_uploader_id string Nickname or id of the playlist uploader
playlist_channel string Display name of the channel that uploaded the playlist
playlist_channel_id string Identifier of the channel that uploaded the playlist
webpage_url string A URL to the video webpage which, if given to yt-dlp, should yield the same result again
webpage_url_basename string The basename of the webpage URL
webpage_url_domain string The domain of the webpage URL
original_url string The URL given by the user (or same as webpage_url for playlist entries)
categories list 视频所属的类别列表
tags list 分配给视频的标签列表
cast list 演员名单

FORMAT SELECTION

默认情况下, yt-dlp 尝试下载最高质量

This is generally equivalent to using -f bestvideo*+bestaudio/best. However, if multiple audiostreams is enabled (--audio-multistreams), the default format changes to -f bestvideo+bestaudio/best. Similarly, if ffmpeg is unavailable, or if you use yt-dlp to stream to stdout (-o -), the default becomes -f best/bestvideo+bestaudio.

QUICK EXAMPLE.

The simplest case is requesting a specific format; e.g. with -f 22 you can download the format with format code equal to 22. You can get the list of available format codes for particular video using --list-formats or -F. Note that these format codes are extractor specific.

You can also use a file extension (currently 3gp, aac, flv, m4a, mp3, mp4, ogg, wav, webm are supported) to download the best quality format of a particular file extension served as a single file, e.g. -f webm will download the best quality format with the webm extension served as a single file.

You can use -f - to interactively provide the format selector for each video

You can also use special names to select particular edge case formats:

name desc
all Select all formats separately
mergeall Select and merge all formats (Must be used with --audio-multistreams, --video-multistreams or both)
b*, best* Select the best quality format that contains either a video or an audio or both (i.e.; vcodec!=none or acodec!=none)
b, best Select the best quality format that contains both video and audio. Equivalent to best*[vcodec!=none][acodec!=none]
bv, bestvideo Select the best quality video-only format. Equivalent to best*[acodec=none]
bv*, bestvideo* Select the best quality format that contains video. It may also contain audio. Equivalent to best*[vcodec!=none]
ba, bestaudio Select the best quality audio-only format. Equivalent to best*[vcodec=none]
ba*, bestaudio* Select the best quality format that contains audio. It may also contain video. Equivalent to best*[acodec!=none] (Do not use!)
w*, worst* Select the worst quality format that contains either a video or an audio
w, worst Select the worst quality format that contains both video and audio. Equivalent to worst*[vcodec!=none][acodec!=none]
wv, worstvideo Select the worst quality video-only format. Equivalent to worst*[acodec=none]
wv*, worstvideo* Select the worst quality format that contains video. It may also contain audio. Equivalent to worst*[vcodec!=none]
wa, worstaudio Select the worst quality audio-only format. Equivalent to worst*[vcodec=none]
wa*, worstaudio* Select the worst quality format that contains audio. It may also contain video. Equivalent to worst*[acodec!=none]

要下载质量最差的视频格式,您可以使用 -f worstvideo。 不过建议不要使用 worst 和相关选项。当你的格式选择器为 worst 时,将选择各方面都最差的格式。大多数情况下,您真正想要的是具有最小文件大小的视频。所以通常最好使用 -S +size,或者更严格地说,-S +size,+br,+res,+fps。 请参阅排序格式了解更多细节。

您可以使用 best<type>.<n> 选择类型的第 n 个最佳格式。 例如 best.2 将选择第二好的组合格式。同样 bv*.3 将选择包含视频流的第三个最佳格式。

如果你想下载多个视频,并且它们没有相同的格式可用,你可以使用 / 指定优先顺序(注意,左侧的格式是首选的)。如 -f 22/17/18 格式 22 可用则优先下载,否则格式 17 可用则优先下载,否则下载格式 18,都不可用会报错没有合适的格式可供下载。

如果您想下载同一视频的几种格式,请使用 , 作为分隔符,例如: -f 22,17,18 将下载所有这三种格式,当然前提是它们可用。或者一个更复杂的例子,结合优先级功能: -f 136/137/mp4/bestvideo,140/m4a/bestaudio

您可以使用 -f <format1>+<format2>+... 将多种格式的视频和音频合并为一个文件(需要安装 ffmpeg)。例如 -f bestvideo+bestaudio 将下载最佳纯视频格式和最佳纯音频格式,并使用 ffmpeg 将它们合并在一起。

Deprecation warning: Since the below described behavior is complex and counter-intuitive, this will be removed and multistreams will be enabled by default in the future. A new operator will be instead added to limit formats to single audio/video

Unless --video-multistreams is used, all formats with a video stream except the first one are ignored. Similarly, unless --audio-multistreams is used, all formats with an audio stream except the first one are ignored. E.g. -f bestvideo+best+bestaudio --video-multistreams --audio-multistreams will download and merge all 3 given formats. The resulting file will have 2 video streams and 2 audio streams. But -f bestvideo+best+bestaudio --no-video-multistreams will download and merge only bestvideo and bestaudio. best is ignored since another format containing a video stream (bestvideo) has already been selected. The order of the formats is therefore important. -f best+bestaudio --no-audio-multistreams will download only best while -f bestaudio+best --no-audio-multistreams will ignore best and download only bestaudio.

Format Selection examples

  1# Download and merge the best video-only format and the best audio-only format,
  2# or download the best combined format if video-only format is not available
  3$ yt-dlp -f "bv+ba/b"
  4
  5# Download best format that contains video,
  6# and if it doesn't already have an audio stream, merge it with best audio-only format
  7$ yt-dlp -f "bv*+ba/b"
  8
  9# 和上面的命令一个效果
 10$ yt-dlp
 11
 12# 分别下载 best-video-only 和 best-audio-only, 不合并
 13# 在这种情况下, output template 必须被指定, 因为默认情况下
 14# bestvideo 和 bestaudio 拥有同样的文件名
 15$ yt-dlp -f "bv,ba" -o "%(title)s.f%(format_id)s.%(ext)s"
 16
 17# Download and merge the best format that has a video stream,
 18# and all audio-only formats into one file
 19$ yt-dlp -f "bv*+mergeall[vcodec=none]" --audio-multistreams
 20
 21# Download and merge the best format that has a video stream,
 22# and the best 2 audio-only formats into one file
 23$ yt-dlp -f "bv*+ba+ba.2" --audio-multistreams
 24
 25
 26# The following examples show the old method (without -S) of format selection
 27# and how to use -S to achieve a similar but (generally) better result
 28
 29# 下载质量最差的(老方法)
 30$ yt-dlp -f "wv*+wa/w"
 31
 32# 下载分辨率最小的中质量最好的视频
 33$ yt-dlp -S "+res"
 34
 35# Download the smallest video available
 36$ yt-dlp -S "+size,+br"
 37
 38
 39# 下载最好的 mp4 格式的视频,如果没有则下载最好的
 40$ yt-dlp -f "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4] / bv*+ba/b"
 41
 42# Download the best video with the best extension
 43# (For video, mp4 > mov > webm > flv. For audio, m4a > aac > mp3 ...)
 44$ yt-dlp -S "ext"
 45
 46
 47# 下载不超过 480p 的最好的视频, 如果没有就下载最差的视频
 48$ yt-dlp -f "bv*[height<=480]+ba/b[height<=480] / wv*+ba/w"
 49
 50# 下载 480p 中的最好的视频, 如果没有, 则下载低于 480p 中最好的
 51$ yt-dlp -S "height:480"
 52
 53# Download the best video available with the largest resolution but no better than 480p,
 54# or the best video with the smallest resolution if there is no video under 480p
 55# Resolution is determined by using the smallest dimension.
 56# So this works correctly for vertical videos as well
 57$ yt-dlp -S "res:480"
 58
 59
 60
 61# Download the best video (that also has audio) but no bigger than 50 MB,
 62# or the worst video (that also has audio) if there is no video under 50 MB
 63$ yt-dlp -f "b[filesize<50M] / w"
 64
 65# Download largest video (that also has audio) but no bigger than 50 MB,
 66# or the smallest video (that also has audio) if there is no video under 50 MB
 67$ yt-dlp -f "b" -S "filesize:50M"
 68
 69# Download best video (that also has audio) that is closest in size to 50 MB
 70$ yt-dlp -f "b" -S "filesize~50M"
 71
 72# 按照分辨率, 拓展格式, 文件大小排序
 73# 值得注意的是, 如果 1080p, mp4 存在, 但是最小的文件都超过了 100M, 依旧会选择
 74$ yt-dlp -S "res:1080,ext,filesize:100M"
 75
 76
 77# Download best video available via direct link over HTTP/HTTPS protocol,
 78# or the best video available via any protocol if there is no such video
 79$ yt-dlp -f "(bv*+ba/b)[protocol^=http][protocol!*=dash] / (bv*+ba/b)"
 80
 81# Download best video available via the best protocol
 82# (https/ftps > http/ftp > m3u8_native > m3u8 > http_dash_segments ...)
 83$ yt-dlp -S "proto"
 84
 85
 86
 87# Download the best video with either h264 or h265 codec,
 88# or the best video if there is no such video
 89$ yt-dlp -f "(bv*[vcodec~='^((he|a)vc|h26[45])']+ba) / (bv*+ba/b)"
 90
 91# Download the best video with best codec no better than h264,
 92# or the best video with worst codec if there is no such video
 93$ yt-dlp -S "codec:h264"
 94
 95# Download the best video with worst codec no worse than h264,
 96# or the best video with best codec if there is no such video
 97$ yt-dlp -S "+codec:h264"
 98
 99
100
101# More complex examples
102
103# Download the best video no better than 720p preferring framerate greater than 30,
104# or the worst video (still preferring framerate greater than 30) if there is no such video
105$ yt-dlp -f "((bv*[fps>30]/bv*)[height<=720]/(wv*[fps>30]/wv*)) + ba / (b[fps>30]/b)[height<=720]/(w[fps>30]/w)"
106
107# Download the video with the largest resolution no better than 720p,
108# or the video with the smallest resolution available if there is no such video,
109# preferring larger framerate for formats with the same resolution
110$ yt-dlp -S "res:720,fps"
111
112
113
114# Download the video with smallest resolution no worse than 480p,
115# or the video with the largest resolution available if there is no such video,
116# preferring better codec and then larger total bitrate for the same resolution
117$ yt-dlp -S "+res:480,codec,br"

Sorting Formats

You can change the criteria for being considered the best by using -S (--format-sort). The general format for this is --format-sort field1,field2....

The available fields are:

name desc
hasvid Gives priority to formats that have a video stream
hasaud Gives priority to formats that have an audio stream
ie_pref The format preference
lang The language preference
quality The quality of the format
source The preference of the source
proto Protocol used for download (https/ftps > http/ftp > m3u8_native/m3u8 > http_dash_segments> websocket_frag > mms/rtsp > f4f/f4m)
vcodec Video Codec (av01 > vp9.2 > vp9 > h265 > h264 > vp8 > h263 > theora > other)
acodec Audio Codec (flac/alac > wav/aiff > opus > vorbis > aac > mp4a > mp3 > ac4 > eac3 > ac3 > dts > other)
codec Equivalent to vcodec,acodec
vext Video Extension (mp4 > mov > webm > flv > other). If --prefer-free-formats is used, webm is preferred.
aext Audio Extension (m4a > aac > mp3 > ogg > opus > webm > other). If --prefer-free-formats is used, the order changes to ogg > opus > webm > mp3 > m4a > aac
ext Equivalent to vext,aext
filesize Exact filesize, if known in advance
fs_approx Approximate filesize
size Exact filesize if available, otherwise approximate filesize
height Height of video
width Width of video
res Video resolution, calculated as the smallest dimension.
fps Framerate of video
hdr The dynamic range of the video (DV > HDR12 > HDR10+ > HDR10 > HLG > SDR)
channels The number of audio channels
tbr Total average bitrate in kbps
vbr Average video bitrate in kbps
abr Average audio bitrate in kbps
br Average bitrate in kbps, tbr/vbr/abr
asr Audio sample rate in Hz

Deprecation warning: Many of these fields have (currently undocumented) aliases, that may be removed in a future version. It is recommended to use only the documented field names.

All fields, unless specified otherwise, are sorted in descending order. To reverse this, prefix the field with a +. E.g. +res prefers format with the smallest resolution. Additionally, you can suffix a preferred value for the fields, separated by a :. E.g. res:720 prefers larger videos, but no larger than 720p and the smallest video if there are no videos less than 720p. For codec and ext, you can provide two preferred values, the first for video and the second for audio. E.g. +codec:avc:m4a (equivalent to +vcodec:avc,+acodec:m4a) sets the video codec preference to h264 > h265 > vp9 > vp9.2 > av01 > vp8 > h263 > theora and audio codec preference to mp4a > aac > vorbis > opus > mp3 > ac3 > dts. You can also make the sorting prefer the nearest values to the provided by using ~ as the delimiter. E.g. filesize~1G prefers the format with filesize closest to 1 GiB.

The fields hasvid and ie_pref are always given highest priority in sorting, irrespective of the user-defined order. This behavior can be changed by using --format-sort-force. Apart from these, the default order used is: lang,quality,res,fps,hdr:12,vcodec:vp9.2,channels,acodec,size,br,asr,proto,ext,hasaud,source,id. The extractors may override this default order, but they cannot override the user-provided order.

Note that the default has vcodec:vp9.2; i.e. av1 is not preferred. Similarly, the default for hdr is hdr:12; i.e. Dolby Vision is not preferred. These choices are made since DV and AV1 formats are not yet fully compatible with most devices. This may be changed in the future as more devices become capable of smoothly playing back these formats.

If your format selector is worst, the last item is selected after sorting. This means it will select the format that is worst in all respects. Most of the time, what you actually want is the video with the smallest filesize instead. So it is generally better to use -f best -S +size,+br,+res,+fps.

Tip: You can use the -v -F to see how the formats have been sorted (worst to best).

CHANGES FROM YOUTUBE-DL

New features

  • Multiple paths and output templates: You can give different output templates and download paths for different types of files. You can also set a temporary path where intermediary files are downloaded to using --paths (-P)

示例:

yt-dlp -P /path/to/download URL

上述命令将所有下载的文件保存到 /path/to/download 目录中。

-P 选项可以接受多个类别的路径,包括视频、缩略图、字幕等。以下是一些常用的类别:

  • home: 下载文件的根目录。
  • temp: 临时文件目录。
  • videos: 视频文件目录。
  • thumbnails: 缩略图目录。
  • subtitles: 字幕目录。

示例

yt-dlp -P "home:/path/to/download" -P "videos:/path/to/videos" -P "thumbnails:/path/to/thumbnails" URL

上述命令将:

  • 所有下载的文件保存到 /path/to/download 目录中。
  • 视频文件保存到 /path/to/videos 目录中。
  • 缩略图保存到 /path/to/thumbnails 目录中。

你可以将 -P 选项与其他 yt-dlp 选项结合使用,例如指定输出模板、格式等:

yt-dlp -f best -o '%(title)s.%(ext)s' -P "videos:~/Downloads/videos" -P "thumbnails:~/Downloads/thumbnails" https://www.youtube.com/watch?v=example_video_id

动态路径

你还可以使用输出模板中的变量来创建动态路径。例如,将视频文件保存到包含上传者名称的目录中:

yt-dlp -P "videos:~/Downloads/%(uploader)s" https://www.youtube.com/watch?v=example_video_id

使用心得

如何使用 --cookies

You may also use a conforming browser extension for exporting cookies, such as Get cookies.txt LOCALLY for Chrome or cookies.txt for Firefox.

下载缩略图并与视频合并

--write-thumbnail + --embed-thumbnail

下载 2560x1440 的 mp4 的,以及和最好的 audio 合并的

yt-dlp -f "bv[height<=1440][ext=mp4]+ba[ext=m4a]/b[height<=1440][ext=mp4]" -o "%(title)s.%(ext)s" https://www.youtube.com/watch?v=example_video_id

在这个命令中:

  • bv[height<=1440][ext=mp4]:选择分辨率不超过 1440p 且格式为 MP4 的最佳视频。
  • ba[ext=m4a]:选择格式为 M4A 的最佳音频。
  • /b[height<=1440][ext=mp4]:如果没有匹配的分离视频和音频格式,则选择分辨率不超过 1440p 且格式为 MP4 的单一文件。
  • 最后其实可以换成 bestvideo+bestaudio:如果没有匹配到 1440p 分辨率的 MP4 视频,则选择最佳视频和最佳音频进行合并。