yt-dlp/yt-dlp

GitHub: yt-dlp/yt-dlp

一款功能丰富的命令行音频/视频下载器,支持多站抓取与自动化运维。

Stars: 156759 | Forks: 12904

[![YT-DLP](https://static.pigsec.cn/wp-content/uploads/repos/2026/04/8e8ca7422d192558.svg)](#readme) [![Release version](https://img.shields.io/github/v/release/yt-dlp/yt-dlp?color=brightgreen&label=Download&style=for-the-badge)](#installation "Installation") [![PyPI](https://img.shields.io/badge/-PyPI-blue.svg?logo=pypi&labelColor=555555&style=for-the-badge)](https://pypi.org/project/yt-dlp) [![Donate](https://img.shields.io/badge/_-Donate-red.svg?logo=githubsponsors&labelColor=555555&style=for-the-badge)](Maintainers.md#maintainers "Donate") [![Discord](https://img.shields.io/discord/807245652072857610?color=blue&labelColor=555555&label=&logo=discord&style=for-the-badge)](https://discord.gg/H5MNcFW63r "Discord") [![Supported Sites](https://img.shields.io/badge/-Supported_Sites-brightgreen.svg?style=for-the-badge)](supportedsites.md "Supported Sites") [![License: Unlicense](https://img.shields.io/badge/-Unlicense-blue.svg?style=for-the-badge)](LICENSE "License") [![CI Status](https://img.shields.io/github/actions/workflow/status/yt-dlp/yt-dlp/core.yml?branch=master&label=Tests&style=for-the-badge)](https://github.com/yt-dlp/yt-dlp/actions "CI Status") [![Commits](https://img.shields.io/github/commit-activity/m/yt-dlp/yt-dlp?label=commits&style=for-the-badge)](https://github.com/yt-dlp/yt-dlp/commits "Commit History") [![Last Commit](https://img.shields.io/github/last-commit/yt-dlp/yt-dlp/master?label=&style=for-the-badge&display_timestamp=committer)](https://github.com/yt-dlp/yt-dlp/pulse/monthly "Last activity")
yt-dlp 是一个功能丰富的命令行音频/视频下载器,支持 [数千个网站](supportedsites.md)。该项目是 [youtube-dl](https://github.com/ytdl-org/youtube-dl) 的分支,基于现已停止维护的 [youtube-dlc](https://github.com/blackjack4494/yt-dlc)。 * [INSTALLATION](#installation) * [Detailed instructions](https://github.com/yt-dlp/yt-dlp/wiki/Installation) * [Release Files](#release-files) * [Update](#update) * [Dependencies](#dependencies) * [Compile](#compile) * [USAGE AND OPTIONS](#usage-and-options) * [General Options](#general-options) * [Network Options](#network-options) * [Geo-restriction](#geo-restriction) * [Video Selection](#video-selection) * [Download Options](#download-options) * [Filesystem Options](#filesystem-options) * [Thumbnail Options](#thumbnail-options) * [Internet Shortcut Options](#internet-shortcut-options) * [Verbosity and Simulation Options](#verbosity-and-simulation-options) * [Workarounds](#workarounds) * [Video Format Options](#video-format-options) * [Subtitle Options](#subtitle-options) * [Authentication Options](#authentication-options) * [Post-processing Options](#post-processing-options) * [SponsorBlock Options](#sponsorblock-options) * [Extractor Options](#extractor-options) * [Preset Aliases](#preset-aliases) * [CONFIGURATION](#configuration) * [Configuration file encoding](#configuration-file-encoding) * [Authentication with netrc](#authentication-with-netrc) * [Notes about environment variables](#notes-about-environment-variables) * [OUTPUT TEMPLATE](#output-template) * [Output template examples](#output-template-examples) * [FORMAT SELECTION](#format-selection) * [Filtering Formats](#filtering-formats) * [Sorting Formats](#sorting-formats) * [Format Selection examples](#format-selection-examples) * [MODIFYING METADATA](#modifying-metadata) * [Modifying metadata examples](#modifying-metadata-examples) * [EXTRACTOR ARGUMENTS](#extractor-arguments) * [PLUGINS](#plugins) * [Installing Plugins](#installing-plugins) * [Developing Plugins](#developing-plugins) * [EMBEDDING YT-DLP](#embedding-yt-dlp) * [Embedding examples](#embedding-examples) * [CHANGES FROM YOUTUBE-DL](#changes-from-youtube-dl) * [New features](#new-features) * [Differences in default behavior](#differences-in-default-behavior) * [Deprecated options](#deprecated-options) * [CONTRIBUTING](CONTRIBUTING.md#contributing-to-yt-dlp) * [Opening an Issue](CONTRIBUTING.md#opening-an-issue) * [Developer Instructions](CONTRIBUTING.md#developer-instructions) * [WIKI](https://github.com/yt-dlp/yt-dlp/wiki) * [FAQ](https://github.com/yt-dlp/yt-dlp/wiki/FAQ) # 安装 [![Windows](https://img.shields.io/badge/-Windows_x64-blue.svg?style=for-the-badge&logo=windows)](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.exe) [![Unix](https://img.shields.io/badge/-Linux/BSD-red.svg?style=for-the-badge&logo=linux)](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp) [![MacOS](https://img.shields.io/badge/-MacOS-lightblue.svg?style=for-the-badge&logo=apple)](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_macos) [![PyPI](https://img.shields.io/badge/-PyPI-blue.svg?logo=pypi&labelColor=555555&style=for-the-badge)](https://pypi.org/project/yt-dlp) [![Source Tarball](https://img.shields.io/badge/-Source_tar-green.svg?style=for-the-badge)](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.tar.gz) [![Other variants](https://img.shields.io/badge/-Other-grey.svg?style=for-the-badge)](#release-files) [![All versions](https://img.shields.io/badge/-All_Versions-lightgrey.svg?style=for-the-badge)](https://github.com/yt-dlp/yt-dlp/releases) 你可以通过 [二进制文件](#release-files)、[pip](https://pypi.org/project/yt-dlp) 或第三方软件包管理器来安装 yt-dlp。请参考 [Wiki](https://github.com/yt-dlp/yt-dlp/wiki/Installation) 获取详细安装说明。 **注意**:手册页、Shell 补全文件等包含在 [源码压缩包](https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp.tar.gz) 中。 ## 更新 如果你使用的是 [发行版二进制文件](#release-files),可以使用 `yt-dlp -U` 进行更新。 如果你是通过 [pip](https://github.com/yt-dlp/yt-dlp/wiki/Installation#with-pip) 安装的,只需重新运行安装命令即可: ```bash pip install -U yt-dlp ``` 对于其他第三方软件包管理器,请参考 [Wiki](https://github.com/yt-dlp/yt-dlp/wiki/Installation) 或查阅其文档。 目前有三个二进制发布通道:`stable`(稳定)、`nightly`(夜间)和 `master`(主分支)。 * `stable` 是默认通道,大多数更新已由用户测试。 * `nightly` 每天午夜 UTC 时间构建一次,包含最新的补丁和变更。推荐普通用户使用此通道。 * `master` 每次推送到主分支后都会构建,包含最新的修复和功能,但可能存在回归问题。 使用 `--update`/`-U` 时,二进制文件只会更新到当前通道。 可以通过 `--update-to CHANNEL` 切换到其他通道,例如: ```bash yt-dlp --update-to stable yt-dlp --update-to stable@2023.07.06 yt-dlp --update-to 2023.10.07 yt-dlp --update-to example/yt-dlp@2023.09.24 ``` **注意**:遇到 `stable` 通道的问题时,建议先升级到 `nightly` 通道再提交错误报告: ``` # To update to nightly from stable executable/binary: yt-dlp --update-to nightly # To install nightly with pip: python -m pip install -U --pre "yt-dlp[default]" ``` 当运行版本超过 90 天未更新时,会显示提醒,建议升级到最新版本。 可以通过添加 `--no-update` 来抑制此提醒。 ## 依赖 Python 3.10+(CPython)和 311+(PyPy)支持。其他版本可能无法正常工作。 ``` yt-dlp [OPTIONS] [--] URL [URL...] ``` 提示:使用 `CTRL`+`F`(或 `Command`+`F`)搜索关键词 ## 通用选项: ``` -h, --help Print this help text and exit --version Print program version and exit -U, --update Update this program to the latest version --no-update Do not check for updates (default) --update-to [CHANNEL]@[TAG] Upgrade/downgrade to a specific version. CHANNEL can be a repository as well. CHANNEL and TAG default to "stable" and "latest" respectively if omitted; See "UPDATE" for details. Supported channels: stable, nightly, master -i, --ignore-errors Ignore download and postprocessing errors. The download will be considered successful even if the postprocessing fails --no-abort-on-error Continue with next video on download errors; e.g. to skip unavailable videos in a playlist (default) --abort-on-error Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors) --list-extractors List all supported extractors and exit --extractor-descriptions Output descriptions of all supported extractors and exit --use-extractors NAMES Extractor names to use separated by commas. You can also use regexes, "all", "default" and "end" (end URL matching); e.g. --ies "holodex.*,end,youtube". Prefix the name with a "-" to exclude it, e.g. --ies default,-generic. Use --list-extractors for a list of extractor names. (Alias: --ies) --default-search PREFIX Use this prefix for unqualified URLs. E.g. "gvsearch2:python" downloads two videos from google videos for the search term "python". Use the value "auto" to let yt-dlp guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching --ignore-config Don't load any more configuration files except those given to --config-locations. For backward compatibility, if this option is found inside the system configuration file, the user configuration is not loaded. (Alias: --no-config) --no-config-locations Do not load any custom configuration files (default). When given inside a configuration file, ignore all previous --config-locations defined in the current file --config-locations PATH Location of the main configuration file; either the path to the config or its containing directory ("-" for stdin). Can be used multiple times and inside other configuration files --plugin-dirs DIR Path to an additional directory to search for plugins. This option can be used multiple times to add multiple directories. Use "default" to search the default plugin directories (default) --no-plugin-dirs Clear plugin directories to search, including defaults and those provided by previous --plugin-dirs --js-runtimes RUNTIME[:PATH] Additional JavaScript runtime to enable, with an optional location for the runtime (either the path to the binary or its containing directory). This option can be used multiple times to enable multiple runtimes. Supported runtimes are (in order of priority, from highest to lowest): deno, node, quickjs, bun. Only "deno" is enabled by default. The highest priority runtime that is both enabled and available will be used. In order to use a lower priority runtime when "deno" is available, --no-js- runtimes needs to be passed before enabling other runtimes --no-js-runtimes Clear JavaScript runtimes to enable, including defaults and those provided by previous --js-runtimes --remote-components COMPONENT Remote components to allow yt-dlp to fetch when required. This option is currently not needed if you are using an official executable or have the requisite version of the yt-dlp-ejs package installed. You can use this option multiple times to allow multiple components. Supported values: ejs:npm (external JavaScript components from npm), ejs:github (external JavaScript components from yt-dlp-ejs GitHub). By default, no remote components are allowed --no-remote-components Disallow fetching of all remote components, including any previously allowed by --remote-components or defaults. --flat-playlist Do not extract a playlist's URL result entries; some entry metadata may be missing and downloading may be bypassed --no-flat-playlist Fully extract the videos of a playlist (default) --live-from-start Download livestreams from the start. Currently experimental and only supported for YouTube, Twitch, and TVer --no-live-from-start Download livestreams from the current time (default) --wait-for-video MIN[-MAX] Wait for scheduled streams to become available. Pass the minimum number of seconds (or range) to wait between retries --no-wait-for-video Do not wait for scheduled streams (default) --mark-watched Mark videos watched (even with --simulate) --no-mark-watched Do not mark videos watched (default) --color [STREAM:]POLICY Whether to emit color codes in output, optionally prefixed by the STREAM (stdout or stderr) to apply the setting to. Can be one of "always", "auto" (default), "never", or "no_color" (use non color terminal sequences). Use "auto-tty" or "no_color-tty" to decide based on terminal support only. Can be used multiple times --compat-options OPTS Options that can help keep compatibility with youtube-dl or youtube-dlc configurations by reverting some of the changes made in yt-dlp. See "Differences in default behavior" for details --alias ALIASES OPTIONS Create aliases for an option string. Unless an alias starts with a dash "-", it is prefixed with "--". Arguments are parsed according to the Python string formatting mini-language. E.g. --alias get-audio,-X "-S aext:{0},abr -x --audio-format {0}" creates options "--get-audio" and "-X" that takes an argument (ARG0) and expands to "-S aext:ARG0,abr -x --audio-format ARG0". All defined aliases are listed in the --help output. Alias options can trigger more aliases; so be careful to avoid defining recursive options. As a safety measure, each alias may be triggered a maximum of 100 times. This option can be used multiple times -t, --preset-alias PRESET Applies a predefined set of options. e.g. --preset-alias mp3. The following presets are available: mp3, aac, mp4, mkv, sleep. See the "Preset Aliases" section at the end for more info. This option can be used multiple times ``` ## 网络选项: ``` --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 --socket-timeout SECONDS Time to wait before giving up, in seconds --source-address IP Client-side IP address to bind to --impersonate CLIENT[:OS] Client to impersonate for requests. E.g. chrome, chrome-110, chrome:windows-10. Pass --impersonate="" to impersonate any client. Note that forcing impersonation for all requests may have a detrimental impact on download speed and stability --list-impersonate-targets List available clients to impersonate. -4, --force-ipv4 Make all connections via IPv4 -6, --force-ipv6 Make all connections via IPv6 --enable-file-urls Enable file:// URLs. This is disabled by default for security reasons. ``` ## 地理限制: ``` --geo-verification-proxy URL Use this proxy to verify the IP address for some geo-restricted sites. The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading --xff VALUE How to fake X-Forwarded-For HTTP header to try bypassing geographic restriction. One of "default" (only when known to be useful), "never", an IP block in CIDR notation, or a two-letter ISO 3166-2 country code ``` ## 视频选择: ``` -I, --playlist-items ITEM_SPEC Comma-separated playlist_index of the items to download. You can specify a range using "[START]:[STOP][:STEP]". For backward compatibility, START-STOP is also supported. Use negative indices to count from the right and negative STEP to download in reverse order. E.g. "-I 1:3,7,-5::2" used on a playlist of size 15 will download the items at index 1,2,3,7,11,13,15 --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 --date DATE Download only videos uploaded on this date. The date can be "YYYYMMDD" or in the format [now|today|yesterday][-N[day|week|month|year]]. E.g. "--date today-2weeks" downloads only videos uploaded on the same day two weeks ago --datebefore DATE Download only videos uploaded on or before this date. The date formats accepted are the same as --date --dateafter DATE Download only videos uploaded on or after this date. The date formats accepted are the same as --date --match-filters FILTER Generic video filter. Any "OUTPUT TEMPLATE" field can be compared with a number or a string using the operators defined in "Filtering Formats". You can also simply specify a field to match if the field is present, use "!field" to check if the field is not present, and "&" to check multiple conditions. Use a "\" to escape "&" or quotes if needed. If used multiple times, the filter matches if at least one of the conditions is met. E.g. --match-filters !is_live --match-filters "like_count>?100 & description~='(?i)\bcats \& dogs\b'" matches only videos that are not live OR those that have a like count more than 100 (or the like field is not available) and also has a description that contains the phrase "cats & dogs" (caseless). Use "--match-filters -" to interactively ask whether to download each video --no-match-filters Do not use any --match-filters (default) --break-match-filters FILTER Same as "--match-filters" but stops the download process when a video is rejected --no-break-match-filters Do not use any --break-match-filters (default) --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 --age-limit YEARS Download only videos suitable for the given age --download-archive FILE Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it --no-download-archive Do not use archive file (default) --max-downloads NUMBER Abort after downloading NUMBER files --break-on-existing Stop the download process when encountering a file that is in the archive supplied with the --download-archive option --no-break-on-existing Do not stop the download process when encountering a file that is in the archive (default) --break-per-input Alters --max-downloads, --break-on-existing, --break-match-filters, and autonumber to reset per input URL --no-break-per-input --break-on-existing and similar options terminates the entire download queue --skip-playlist-after-errors N Number of allowed failures until the rest of the playlist is skipped ``` ## 下载选项: ``` -N, --concurrent-fragments N Number of fragments of a dash/hlsnative video that should be downloaded concurrently (default is 1) -r, --limit-rate RATE Maximum download rate in bytes per second, e.g. 50K or 4.2M --throttled-rate RATE Minimum download rate in bytes per second below which throttling is assumed and the video data is re-extracted, e.g. 100K -R, --retries RETRIES Number of retries (default is 10), or "infinite" --file-access-retries RETRIES Number of times to retry on file access error (default is 3), or "infinite" --fragment-retries RETRIES Number of retries for a fragment (default is 10), or "infinite" (DASH, hlsnative and ISM) --retry-sleep [TYPE:]EXPR Time to sleep between retries in seconds (optionally) prefixed by the type of retry (http (default), fragment, file_access, extractor) to apply the sleep to. EXPR can be a number, linear=START[:END[:STEP=1]] or exp=START[:END[:BASE=2]]. This option can be used multiple times to set the sleep for the different retry types, e.g. --retry-sleep linear=1::2 --retry-sleep fragment:exp=1:20 --skip-unavailable-fragments Skip unavailable fragments for DASH, hlsnative and ISM downloads (default) (Alias: --no-abort-on-unavailable-fragments) --abort-on-unavailable-fragments Abort download if a fragment is unavailable (Alias: --no-skip-unavailable-fragments) --keep-fragments Keep downloaded fragments on disk after downloading is finished --no-keep-fragments Delete downloaded fragments after downloading is finished (default) --buffer-size SIZE Size of download buffer, e.g. 1024 or 16K (default is 1024) --resize-buffer The buffer size is automatically resized from an initial value of --buffer-size (default) --no-resize-buffer Do not automatically adjust the buffer size --http-chunk-size SIZE Size of a chunk for chunk-based HTTP downloading, e.g. 10485760 or 10M (default is disabled). May be useful for bypassing bandwidth throttling imposed by a webserver (experimental) --playlist-random Download playlist videos in random order --lazy-playlist Process entries in the playlist as they are received. This disables n_entries, --playlist-random and --playlist-reverse --no-lazy-playlist Process videos in the playlist only after the entire playlist is parsed (default) --hls-use-mpegts Use the mpegts container for HLS videos; allowing some players to play the video while downloading, and reducing the chance of file corruption if download is interrupted. This is enabled by default for live streams --no-hls-use-mpegts Do not use the mpegts container for HLS videos. This is default when not downloading live streams --download-sections REGEX Download only chapters that match the regular expression. A "*" prefix denotes time-range instead of chapter. Negative timestamps are calculated from the end. "*from-url" can be used to download between the "start_time" and "end_time" extracted from the URL. Needs ffmpeg. This option can be used multiple times to download multiple sections, e.g. --download-sections "*10:15-inf" --download-sections "intro" --downloader [PROTO:]NAME Name or path of the external downloader to use (optionally) prefixed by the protocols (http, ftp, m3u8, dash, rstp, rtmp, mms) to use it for. Currently supports native, aria2c, axel, curl, ffmpeg, httpie, wget. You can use this option multiple times to set different downloaders for different protocols. E.g. --downloader aria2c --downloader "dash,m3u8:native" will use aria2c for http/ftp downloads, and the native downloader for dash/m3u8 downloads (Alias: --external-downloader) --downloader-args NAME:ARGS Give these arguments to the external downloader. Specify the downloader name and the arguments separated by a colon ":". For ffmpeg, arguments can be passed to different positions using the same syntax as --postprocessor-args. You can use this option multiple times to give different arguments to different downloaders (Alias: --external-downloader-args) ``` ## 文件系统选项: ``` -a, --batch-file FILE File containing URLs to download ("-" for stdin), one URL per line. Lines starting with "#", ";" or "]" are considered as comments and ignored --no-batch-file Do not read URLs from batch file (default) -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") --restrict-filenames Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames --no-restrict-filenames Allow Unicode characters, "&" and spaces in filenames (default) --windows-filenames Force filenames to be Windows-compatible --no-windows-filenames Sanitize filenames only minimally --trim-filenames LENGTH Limit the filename length (excluding extension) to the specified number of characters -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 --no-mtime Do not use the Last-modified header to set the file modification time (default) --write-description Write video description to a .description file --no-write-description Do not write video description (default) --write-info-json Write video metadata to a .info.json file (this may contain personal information) --no-write-info-json Do not write video metadata (default) --write-playlist-metafiles Write playlist metadata in addition to the video metadata when using --write-info-json, --write-description etc. (default) --no-write-playlist-metafiles Do not write playlist metadata when using --write-info-json, --write-description etc. --clean-info-json Remove some internal metadata such as filenames from the infojson (default) --no-clean-info-json Write all fields to the infojson --write-comments Retrieve video comments to be placed in the infojson. The comments are fetched even without this option if the extraction is known to be quick (Alias: --get-comments) --no-write-comments Do not retrieve video comments unless the extraction is known to be quick (Alias: --no-get-comments) --load-info-json FILE JSON file containing the video information (created with the "--write-info-json" option) --cookies FILE Netscape formatted file to read cookies from and dump cookie jar in --no-cookies Do not read/dump cookies from/to file (default) --cookies-from-browser BROWSER[+KEYRING][:PROFILE][::CONTAINER] The name of the browser to load cookies from. Currently supported browsers are: brave, chrome, chromium, edge, firefox, opera, safari, vivaldi, whale. Optionally, the KEYRING used for decrypting Chromium cookies on Linux, the name/path of the PROFILE to load cookies from, and the CONTAINER name (if Firefox) ("none" for no container) can be given with their respective separators. By default, all containers of the most recently accessed profile are used. Currently supported keyrings are: basictext, gnomekeyring, kwallet, kwallet5, kwallet6 --no-cookies-from-browser Do not load cookies from browser (default) --cache-dir DIR Location in the filesystem where yt-dlp can store some downloaded information (such as client ids and signatures) permanently. By default ${XDG_CACHE_HOME}/yt-dlp --no-cache-dir Disable filesystem caching --rm-cache-dir Delete all filesystem cache files ``` ## 缩略图选项: ``` --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 快捷方式选项: ``` --write-link Write an internet shortcut file, depending on the current platform (.url, .webloc or .desktop). The URL may be cached by the OS --write-url-link Write a .url Windows internet shortcut. The OS caches the URL based on the file path --write-webloc-link Write a .webloc macOS internet shortcut --write-desktop-link Write a .desktop Linux internet shortcut ``` ## 详细信息和模拟选项: ``` -q, --quiet Activate quiet mode. If used with --verbose, print the log to stderr --no-quiet Deactivate quiet mode. (Default) --no-warnings Ignore warnings -s, --simulate Do not download the video and do not write anything to disk --no-simulate Download the video even if printing/listing options are used --ignore-no-formats-error Ignore "No video formats" error. Useful for extracting metadata even if the videos are not actually available for download (experimental) --no-ignore-no-formats-error Throw error when no downloadable video formats are found (default) --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 --print-to-file [WHEN:]TEMPLATE FILE Append given template to the file. The values of WHEN and TEMPLATE are the same as that of --print. FILE uses the same syntax as the output template. This option can be used multiple times -j, --dump-json Quiet, but print JSON information for each video. Simulate unless --no-simulate is used. See "OUTPUT TEMPLATE" for a description of available keys -J, --dump-single-json Quiet, but print JSON information for each URL or infojson passed. Simulate unless --no-simulate is used. If the URL refers to a playlist, the whole playlist information is dumped in a single line --force-write-archive Force download archive entries to be written as far as no errors occur, even if -s or another simulation option is used (Alias: --force-download-archive) --newline Output progress bar as new lines --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) -v, --verbose Print various debugging information --dump-pages Print downloaded pages encoded using base64 to debug problems (very verbose) --write-pages Write downloaded intermediary pages to files in the current directory to debug problems --print-traffic Display sent and read HTTP traffic ``` ## 修复措施: ``` --encoding ENCODING Force the specified encoding (experimental) --legacy-server-connect Explicitly allow HTTPS connection to servers that do not support RFC 5746 secure renegotiation --no-check-certificates Suppress HTTPS certificate validation --prefer-insecure Use an unencrypted connection to retrieve information about the video (Currently supported only for YouTube) --add-headers FIELD:VALUE Specify a custom HTTP header and its value, separated by a colon ":". You can use this option multiple times --bidi-workaround Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH --sleep-requests SECONDS Number of seconds to sleep between requests during data extraction --sleep-interval SECONDS Number of seconds to sleep before each download. This is the minimum time to sleep when used along with --max-sleep-interval (Alias: --min-sleep-interval) --max-sleep-interval SECONDS Maximum number of seconds to sleep. Can only be used along with --min-sleep-interval --sleep-subtitles SECONDS Number of seconds to sleep before each subtitle download ``` ## 视频格式选项: ``` -f, --format FORMAT Video format code, see "FORMAT SELECTION" for more details -S, --format-sort SORTORDER Sort the formats by the fields given, see "Sorting Formats" for more details --format-sort-reset Disregard previous user specified sort order and reset to the default --format-sort-force Force user specified sort order to have precedence over all fields, see "Sorting Formats" for more details (Alias: --S-force) --no-format-sort-force Some fields have precedence over the user specified sort order (default) --video-multistreams Allow multiple video streams to be merged into a single file --no-video-multistreams Only one video stream is downloaded for each output file (default) --audio-multistreams Allow multiple audio streams to be merged into a single file --no-audio-multistreams Only one audio stream is downloaded for each output file (default) --prefer-free-formats Prefer video formats with free containers over non-free ones of the same quality. Use with "-S ext" to strictly prefer free containers irrespective of quality --no-prefer-free-formats Don't give any special preference to free containers (default) --check-formats Make sure formats are selected only from those that are actually downloadable --check-all-formats Check all formats for whether they are actually downloadable --no-check-formats Do not check that the formats are actually downloadable -F, --list-formats List available formats of each video. Simulate unless --no-simulate is used --merge-output-format FORMAT Containers that may be used when merging formats, separated by "/", e.g. "mp4/mkv". Ignored if no merge is required. (currently supported: avi, flv, mkv, mov, mp4, webm) ``` ## 字幕选项: ``` --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 separated by "/", 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" (where "en.*" is a regex pattern that matches "en" followed by 0 or more of any character). 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 ``` ## 认证选项: ``` -u, --username USERNAME Login with this account ID -p, --password PASSWORD Account password. If this option is left out, yt-dlp will ask interactively -2, --twofactor TWOFACTOR Two-factor authentication code -n, --netrc Use .netrc authentication data --netrc-location PATH Location of .netrc authentication data; either the path or its containing directory. Defaults to ~/.netrc --netrc-cmd NETRC_CMD Command to execute to get the credentials for an extractor. --video-password PASSWORD Video-specific password --ap-mso MSO Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs --ap-username USERNAME Multiple-system operator account login --ap-password PASSWORD Multiple-system operator account password. If this option is left out, yt-dlp will ask interactively --ap-list-mso List all supported multiple-system operators --client-certificate CERTFILE Path to client certificate file in PEM format. May include the private key --client-certificate-key KEYFILE Path to private key file for client certificate --client-certificate-password PASSWORD Password for client certificate private key, if encrypted. If not provided, and the key is encrypted, yt-dlp will ask interactively ``` ## 后处理选项: ``` -x, --extract-audio Convert video files to audio-only files (requires ffmpeg and ffprobe) --audio-format FORMAT Format to convert the audio to when -x is used. (currently supported: best (default), aac, alac, flac, m4a, mp3, opus, vorbis, wav). You can specify multiple rules using similar syntax as --remux-video --audio-quality QUALITY Specify ffmpeg audio quality to use when converting the audio with -x. Insert a value between 0 (best) and 10 (worst) for VBR or a specific bitrate like 128K (default 5) --remux-video FORMAT Remux the video into another container if necessary (currently supported: avi, flv, gif, mkv, mov, mp4, webm, aac, aiff, alac, flac, m4a, mka, mp3, ogg, opus, vorbis, wav). If the target container does not support the video/audio codec, remuxing will fail. You can specify multiple rules; e.g. "aac>m4a/mov>mp4/mkv" will remux aac to m4a, mov to mp4 and anything else to mkv --recode-video FORMAT Re-encode the video into another format if necessary. The syntax and supported formats are the same as --remux-video --postprocessor-args NAME:ARGS Give these arguments to the postprocessors. Specify the postprocessor/executable name and the arguments separated by a colon ":" to give the argument to the specified postprocessor/executable. Supported PP are: Merger, ModifyChapters, SplitChapters, ExtractAudio, VideoRemuxer, VideoConvertor, Metadata, EmbedSubtitle, EmbedThumbnail, SubtitlesConvertor, ThumbnailsConvertor, FixupStretched, FixupM4a, FixupM3u8, FixupTimestamp and FixupDuration. The supported executables are: AtomicParsley, FFmpeg and FFprobe. You can also specify "PP+EXE:ARGS" to give the arguments to the specified executable only when being used by the specified postprocessor. Additionally, for ffmpeg/ffprobe, "_i"/"_o" can be appended to the prefix optionally followed by a number to pass the argument before the specified input/output file, e.g. --ppa "Merger+ffmpeg_i1:-v quiet". You can use this option multiple times to give different arguments to different postprocessors. (Alias: --ppa) -k, --keep-video Keep the intermediate video file on disk after post-processing --no-keep-video Delete the intermediate video file after post-processing (default) --post-overwrites Overwrite post-processed files (default) --no-post-overwrites Do not overwrite post-processed files --embed-subs Embed subtitles in the video (only for mp4, webm and mkv videos) --no-embed-subs Do not embed subtitles (default) --embed-thumbnail Embed thumbnail in the video as cover art --no-embed-thumbnail Do not embed thumbnail (default) --embed-metadata Embed metadata to the video file. Also embeds chapters/infojson if present unless --no-embed-chapters/--no-embed-info-json are used (Alias: --add-metadata) --no-embed-metadata Do not add metadata to file (default) (Alias: --no-add-metadata) --embed-chapters Add chapter markers to the video file (Alias: --add-chapters) --no-embed-chapters Do not add chapter markers (default) (Alias: --no-add-chapters) --embed-info-json Embed the infojson as an attachment to mkv/mka video files --no-embed-info-json Do not embed the infojson as an attachment to the video file --parse-metadata [WHEN:]FROM:TO Parse additional metadata like title/artist from other fields; see "MODIFYING METADATA" for details. Supported values of "WHEN" are the same as that of --use-postprocessor (default: pre_process) --replace-in-metadata [WHEN:]FIELDS REGEX REPLACE Replace text in a metadata field using the given regex. This option can be used multiple times. Supported values of "WHEN" are the same as that of --use-postprocessor (default: pre_process) --xattrs Write metadata to the video file's xattrs (using Dublin Core and XDG standards) --concat-playlist POLICY Concatenate videos in a playlist. One of "never", "always", or "multi_video" (default; only when the videos form a single show). All the video files must have the same codecs and number of streams to be concatenable. The "pl_video:" prefix can be used with "--paths" and "--output" to set the output filename for the concatenated files. See "OUTPUT TEMPLATE" for details --fixup POLICY Automatically correct known faults of the file. One of never (do nothing), warn (only emit a warning), detect_or_warn (the default; fix the file if we can, warn otherwise), force (try fixing even if the file already exists) --ffmpeg-location PATH Location of the ffmpeg binary; either the path to the binary or its containing directory --exec [WHEN:]CMD Execute a command, optionally prefixed with when to execute it, separated by a ":". Supported values of "WHEN" are the same as that of --use-postprocessor (default: after_move). The same syntax as the output template can be used to pass any field as arguments to the command. If no fields are passed, %(filepath,_filename|)q is appended to the end of the command. This option can be used multiple times --no-exec Remove any previously defined --exec --convert-subs FORMAT Convert the subtitles to another format (currently supported: ass, lrc, srt, vtt). Use "--convert-subs none" to disable conversion (default) (Alias: --convert- subtitles) --convert-thumbnails FORMAT Convert the thumbnails to another format (currently supported: jpg, png, webp). You can specify multiple rules using similar syntax as "--remux-video". Use "--convert- thumbnails none" to disable conversion (default) --split-chapters Split video into multiple files based on internal chapters. The "chapter:" prefix can be used with "--paths" and "--output" to set the output filename for the split files. See "OUTPUT TEMPLATE" for details --no-split-chapters Do not split video based on chapters (default) --remove-chapters REGEX Remove chapters whose title matches the given regular expression. The syntax is the same as --download-sections. This option can be used multiple times --no-remove-chapters Do not remove any chapters from the file (default) --force-keyframes-at-cuts Force keyframes at cuts when downloading/splitting/removing sections. This is slow due to needing a re-encode, but the resulting video may have fewer artifacts around the cuts --no-force-keyframes-at-cuts Do not force keyframes around the chapters when cutting/splitting (default) --use-postprocessor NAME[:ARGS] The (case-sensitive) name of plugin postprocessors to be enabled, and (optionally) arguments to be passed to it, separated by a colon ":". ARGS are a semicolon ";" delimited list of NAME=VALUE. The "when" argument determines when the postprocessor is invoked. It can be one of "pre_process" (after video extraction), "after_filter" (after video passes filter), "video" (after --format; before --print/--output), "before_dl" (before each video download), "post_process" (after each video download; default), "after_move" (after moving the video file to its final location), "after_video" (after downloading and processing all formats of a video), or "playlist" (at end of playlist). This option can be used multiple times to add different postprocessors ``` ## 赞助商屏蔽选项: 为章节条目创建赞助商屏蔽,或删除各种片段(赞助商、介绍等) 从 YouTube 视频中删除使用 [赞助商屏蔽 API](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) 的章节条目,或删除介绍等内容。 ``` --sponsorblock-mark CATS SponsorBlock categories to create chapters for, separated by commas. Available categories are sponsor, intro, outro, selfpromo, preview, filler, interaction, music_offtopic, hook, poi_highlight, chapter, all and default (=all). You can prefix the category with a "-" to exclude it. See [1] for descriptions of the categories. E.g. --sponsorblock-mark all,-preview [1] https://wiki.sponsor.ajay.app/w/Segment_Categories --sponsorblock-remove CATS SponsorBlock categories to be removed from the video file, separated by commas. If a category is present in both mark and remove, remove takes precedence. The syntax and available categories are the same as for --sponsorblock-mark except that "default" refers to "all,-filler" and poi_highlight, chapter are not available --sponsorblock-chapter-title TEMPLATE An output template for the title of the SponsorBlock chapters created by --sponsorblock-mark. The only available fields are start_time, end_time, category, categories, name, category_names. Defaults to "[SponsorBlock]: %(category_names)l" --no-sponsorblock Disable both --sponsorblock-mark and --sponsorblock-remove --sponsorblock-api URL SponsorBlock API location, defaults to https://sponsor.ajay.app ``` ## 提取器选项: ``` --extractor-retries RETRIES Number of retries for known extractor errors (default is 3), or "infinite" --allow-dynamic-mpd Process dynamic DASH manifests (default) (Alias: --no-ignore-dynamic-mpd) --ignore-dynamic-mpd Do not process dynamic DASH manifests (Alias: --no-allow-dynamic-mpd) --hls-split-discontinuity Split HLS playlists to different formats at discontinuities such as ad breaks --no-hls-split-discontinuity Do not split HLS playlists into different formats at discontinuities such as ad breaks (default) --extractor-args IE_KEY:ARGS Pass ARGS arguments to the IE_KEY extractor. See "EXTRACTOR ARGUMENTS" for details. You can use this option multiple times to give arguments for different extractors ``` ## 预设别名: 为方便使用和易于理解,预先定义了别名。请注意,yt-dlp 的未来版本可能会添加或调整预设,但现有预设名称不会更改或删除。 ``` -t mp3 -f 'ba[acodec^=mp3]/ba/b' -x --audio-format mp3 -t aac -f 'ba[acodec^=aac]/ba[acodec^=mp4a.40.]/ba/b' -x --audio-format aac -t mp4 --merge-output-format mp4 --remux-video mp4 -S vcodec:h264,lang,quality,res,fps,hdr:12,a codec:aac -t mkv --merge-output-format mkv --remux-video mkv -t sleep --sleep-subtitles 5 --sleep-requests 0.75 --sleep-interval 10 --max-sleep-interval 20 ``` # 配置 你可以通过将任何受支持的命令行选项放入配置文件来配置 yt-dlp。加载配置的顺序如下: 1. **主配置**: - 通过 `--config-locations` 指定的文件 2. **便携配置**:(推荐用于便携安装) - 二进制文件所在目录的 `yt-dlp.conf` - 如果从源代码运行,则为 `yt-dlp.conf` 的父目录中的 `yt-dlp.conf` 3. **主目录配置**: - `yt-dlp.conf` 在 `-P` 指定的主目录中 - 如果未指定 `-P`,则搜索当前目录 4. **用户配置**: - `${XDG_CONFIG_HOME}/yt-dlp.conf` - `${XDG_CONFIG_HOME}/yt-dlp/config`(Linux/macOS 推荐) - `${XDG_CONFIG_HOME}/yt-dlp/config.txt` - `${APPDATA}/yt-dlp.conf` - `${APPDATA}/yt-dlp/config`(推荐在 Windows 上) - `${APPDATA}/yt-dlp/config.txt` - `~/yt-dlp.conf` - `~/yt-dlp.conf.txt` - `~/.yt-dlp/config` - `~/.yt-dlp/config.txt` 例如,使用以下配置文件,yt-dlp 将始终提取音频、复制修改时间、使用代理,并将所有视频保存在主目录下的 `YouTube` 文件夹中: ``` # Lines starting with # are comments # Always extract audio -x # Copy the mtime --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 中一样。 可以使用 `--ignore-config` 忽略所有配置文件。如果 `--ignore-config` 在某个配置文件中找到,则不会加载后续配置。例如,将该选项放在便携配置文件中可阻止加载主目录、用户和系统配置。 此外(出于向后兼容性),如果 `--ignore-config` 在系统配置文件中找到,则不会加载用户配置。 ### 配置文件编码 根据系统区域设置解码配置文件,如果存在 UTF BOM 则使用 UTF-8,否则使用系统区域设置。 如果希望以不同编码方式解码文件,请在文件开头添加 `# coding: ENCODING`(例如 `# coding: shift-jis`)。开头不能有任何字符,包括空格或 BOM。 ### 使用 netrc 进行认证 你可能希望为支持认证的提取器配置自动存储凭据(通过提供用户名和密码),以避免每次运行 yt-dlp 时都将凭据作为命令行参数传递,并防止在 Shell 命令历史中记录明文密码。你可以使用 [`.netrc` 文件](https://link.zhihu.com/?target=https%3A%2F%2Fen.wikipedia.org/wiki/.netrc) 来实现此目的。 为此,需要在 `--netrc-location` 指定的位置创建一个 `.netrc` 文件并限制权限仅供读写: ``` touch ${HOME}/.netrc chmod a-rwx,u+rw ${HOME}/.netrc ``` 之后,可以按以下格式为提取器添加凭据,其中 *extractor* 是提取器名称的小写形式: ``` machine login password ``` 例如: ``` machine youtube login myaccount@gmail.com password my_youtube_password machine twitch login my_twitch_account_name password my_twitch_password ``` 要激活使用 `.netrc` 文件的认证,应传递 `--netrc` 给 yt-dlp 或将其放在 [配置文件中](#configuration)。 作为使用 `.netrc` 文件的替代方案,可以配置自定义 shell 命令来提供提取器的凭据。这通过提供 `--netrc-cmd` 参数实现,该参数应输出凭据的 netrc 格式并返回 0 表示成功,其他值将被视为错误。 例如,要使用加密的 `.netrc` 文件(存储为 `.authinfo.gpg`): ``` yt-dlp --netrc-cmd 'gpg --decrypt ~/.authinfo.gpg' 'https://www.youtube.com/watch?v=BaW_jenozKc' ``` ### 关于环境变量的说明 * 环境变量通常指定为 `${VARIABLE}`/`$VARIABLE`(UNIX)和 `%VARIABLE%`(Windows);但文档中始终显示为 `${VARIABLE}` * yt-dlp 也允许在 Windows 上使用 UNIX 风格的环境变量用于路径类选项;例如 `--output`、`--config-locations` * 如果未设置,`${XDG_CONFIG_HOME}` 默认为 `~/.config`,`${XDG_CACHE_HOME}` 默认为 `~/.cache` * 在 Windows 上,`~` 指向 `${HOME}`(如果存在);否则指向 `${USERPROFILE}` 或 `${HOMEDRIVE}${HOMEPATH}` * 在 Windows 上,`${USERPROFILE}` 通常指向 `C:\Users\<用户名>`,`${APPDATA}` 指向 `${USERPROFILE}\AppData\Roaming` # 输出模板 `-o` 选项用于指定输出文件名模板,`-P` 选项用于指定各类文件的保存路径。 **简述**:[导航到示例](#output-template-examples)。 最简单的用法是不设置任何模板参数直接下载单个文件,例如 `yt-dlp -o funny_video.flv "https://some/video"`(不推荐硬编码文件扩展名,这样可能会破坏后处理)。 但模板也可以包含在下载每个视频时会被替换的特殊序列。特殊序列可以按照 [Python 字符串格式化操作](https://docs.python.org/3/library/string.html) 进行格式化,例如 `%(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. **算术运算**:可以对数字字段进行简单的算术运算;例如 `%(playlist_index+10)03d`、`%(n_entries+1-playlist_index)d` 3. **日期/时间格式化**:日期时间字段可以按照 [strftime 格式化](httpsdocs.python.org/3/library/datetime.html#strftime-and-strptime-format) 进行格式化;例如 `%(duration>%H-%M-%S)s`、`%(upload_date>%Y-%m-%d)s`、`%(epoch-3600>%H-%M-%S)s` 4. **备选字段**:可以使用逗号分隔备选字段;例如 `%(release_date>%Y,upload_date>%Y|Unknown)s` 5. **替换**:可以使用 `&` 分隔符按照 [`str.format` 小语言](https://docs.python.org/3/library/string.html#format-string-syntax) 进行替换。如果字段非空,则使用此替换值而非实际字段内容。这在备选字段之后考虑;因此替换值会在任意备选字段非空时使用。例如 `%(chapters&has chapters|no chapters)s`、`%(title&TITLE={:>20}|NO TITLE)s` 6. **默认值**:可以使用 `|` 分隔符指定字段的默认值,覆盖 `--output-na-placeholder`;例如 `%(uploader|Unknown)s` 7. **更多转换**:除了常规格式类型 `diouxXeEfFgGcrs`,yt-dlp 还支持转换为 `B` = **B**ytes、`j` = **j**son(`#` 用于美化打印,`+` 用于 Unicode)、`h` = HTML 转义、`l` = 逗号分隔的**列表**(`#` 用于换行符分隔)、`q` = 字符串**引用**(`#` 用于拆分列表为不同参数)、`D` = 添加**D**ecimal 后缀(`#` 用于使用 1024 作为因子),以及 `S` = **S**anitize 作为文件名(`**` 用于受限字符)。 8. **Unicode 规范化**:格式类型 `U` 可用于 NFC [Unicode 规范化](https://unicode.org/reports/tr15/)。备选形式标志(`#`)可更改为 NFD,转换标志(`+`)可用于 NFKC/NFKD 兼容性等价规范化。例如 `%(title)+.100U` 是 NFKC。 总结来说,字段的一般语法为: ``` %(name[.keys][addition][>strf][,alternate][&replacement][|default])[flags][width][.precision][length]type ``` 此外,可以为各种元数据文件单独设置输出模板(而非通用模板),文件类型包括 `subtitle`、`thumbnail`、`description`、`annotation`(已弃用)、`infojson`、`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:"` 仅对播放列表写入缩略图,而不写入视频。 **注意**:由于后处理(例如合并等),实际输出文件名可能不同。使用 `--print after_move:filepath` 查看后处理完成后的文件名。 可用字段包括: - `id`(字符串):视频标识符 - `title`(字符串):视频标题 - `fulltitle`(字符串):视频标题(忽略直播时间戳和通用标题) - `ext`(字符串):视频文件扩展名 - `alt_title`(字符串):视频副标题 - `description`(字符串):视频描述 - `display_id`(字符串):视频的替代标识符 - `uploader`(字符串):视频上传者全名 - `uploader_id`(字符串):视频上传者昵称或 ID - `uploader_url`(字符串):上传者个人资料 URL - `license`(字符串):视频授权许可 - `creators`(列表):视频创作者 - `creator`(字符串):视频创作者(逗号分隔) - `timestamp`(数字):视频可用时间的时间戳 - `upload_date`(字符串):视频上传日期(UTC,格式 YYYYMMDD) - `release_timestamp`(数字):视频发布时间的时间戳 - `release_date`(字符串):视频发布日期(UTC,格式 YYYYMMDD) - `release_year`(数字):视频或专辑发布年份 - `modified_timestamp`(数字):视频最后修改时间的时间戳 - `modified_date`(字符串):视频最后修改日期(UTC,格式 YYYYMMDD) - `channel`(字符串):上传视频的频道全名 - `channel_id`(字符串):频道 ID - `channel_url`(字符串):频道 URL - `channel_follower_count`(数字):频道关注者数量 - `channel_is_verified`(布尔值):频道是否已验证 - `location`(字符串):视频拍摄地点 - `duration`(数字):视频时长(秒) - `duration_string`(字符串):视频时长(HH:mm:ss) - `view_count`(数字):观看次数 - `concurrent_view_count`(数字):当前观看次数 - `like_count`(数字):点赞数 - `dislike_count`(数字):点踩数 - `repost_count`(数字):转发数 - `average_rating`(数字):平均评分 - `comment_count`(数字):评论数 - `save_count`(数字):保存或收藏次数 - `age_limit`(数字):年龄限制(年) - `live_status`(字符串):直播状态(not_live、is_live、is_upcoming、was_live、post_live) - `is_live`(布尔值):是否为直播 - `was_live`(布尔值):是否曾是直播 - `playable_in_embed`(字符串):是否允许嵌入播放 - `availability`(字符串):可用性(private、premium_only、subscriber_only、needs_auth、unlisted、public) - `media_type`(字符串):媒体类型(如 episode、clip、trailer) - `start_time`(数字):开始时间(秒) - `end_time`(数字):结束时间(秒) - `extractor`(字符串):提取器名称 - `extractor_key`(字符串):提取器键 - `epoch`(数字):信息提取完成的 Unix 时间戳 - `autonumber`(数字):自动编号,从 `--autonumber-start` 开始 - `video_autonumber`(数字):视频自动编号 - `n_entries`(数字):提取的项目总数 - `playlist_id`(字符串):播放列表 ID - `playlist_title`(字符串):播放列表标题 - `playlist`(字符串):播放列表标题或 ID - `playlist_count`(数字):播放列表中的项目总数 - `playlist_index`(数字):视频在播放列表中的索引(补零) - `playlist_autonumber`(数字):视频在播放队列中的位置(补零) - `playlist_uploader`(字符串):播放列表上传者 - `playlist_uploader_id`(字符串):播放列表上传者 ID - `playlist_channel`(字符串):播放列表频道显示名 - `playlist_channel_id`(字符串):播放列表频道 ID - `playlist_webpage_url`(字符串):播放列表网页 URL - `webpage_url`(字符串):视频网页 URL - `webpage_url_basename`(字符串):网页 URL 的基础名 - `webpage_url_domain`(字符串):网页 URL 的域名 - `original_url`(字符串):用户提供的原始 URL - `categories`(列表):视频所属类别 - `tags`(列表):视频标签 - `cast`(列表):演员列表 所有上述字段在 [格式化过滤器](#filtering-formats) 中也可使用。 对于属于某个逻辑章节或部分的视频: - `chapter`(字符串):章节名称或标题 - `chapter_number`(数字):章节编号 - `chapter_id`(字符串):章节 ID 对于作为系列或节目一部分的剧集: - `series`(字符串):系列或节目标题 - `series_id`(字符串):系列或节目 ID - `season`(字符串):季标题 - `season_number`(数字):季编号 - `season_id`(字符串):季 ID - `episode`(字符串):剧集标题 - `episode_number`(数字):季内剧集编号 - `episode_id`(字符串):剧集 ID 对于作为音乐专辑一部分的音轨: - `track`(字符串):音轨标题 - `track_number`(数字):音轨编号 - `track_id`(字符串):音轨 - `artists`(列表):艺术家列表 - `artist`(字符串):艺术家(逗号分隔) - `genres`(列表):流派列表 - `genre`(字符串):流派(逗号分隔) - `composers`(列表):作曲家列表 - `composer`(字符串):作曲家(逗号分隔) - `album`(字符串):专辑标题 - `album_type`(字符串):专辑类型 - `album_artists`(列表):专辑所有艺术家 - `album_artist`(字符串):专辑所有艺术家(逗号分隔) - `disc_number`(数字):光盘编号 仅在使用 `--download-sections` 并针对具有内部章节的视频启用 `--split-chapters` 时可用: - `section_title`(字符串):章节标题 - `section_number`(数字):章节编号 - `section_start`(数字):章节开始时间(秒) - `section_end`(数字):章节结束时间(秒) 仅在使用 `--print` 时可用: - `urls`(字符串):所有请求格式的 URL,每行一个 - `filename`(字符串):视频文件名。请注意,实际文件名可能不同。 - `formats_table`(表格):视频格式表(通过 `--list-formats` 打印) - `thumbnails_table`(表格):缩略图格式表(通过 `--list-thumbnails` 打印) - `subtitles_table`(表格):字幕格式表(通过 `--list-subs` 打印) - `automatic_captions_table`(表格):自动字幕格式表(通过 `--list-subs` 打印) 下载后(`post_process`/`after_move`): - `filepath`(字符串):实际下载视频文件的路径 仅在使用 `--sponsorblock-chapter-title` 时可用: - `start_time`(数字):章节开始时间(秒) - `end_time`(数字):章节结束时间(秒) - `categories`(列表):章节所属的 [SponsorBlock 类别](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) - `category`(字符串):最小的 SponsorBlock 类别 - `category_names`(列表):类别的友好名称 - `name`(字符串):最小类别的友好名称 - `type`(字符串):章节的 [SponsorBlock 动作类型](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) 每个上述序列在输出模板中引用时将被替换为对应的实际值。例如,对于 `-o %(title)s-%(id)s.%(ext)s` 和一个 mp4 视频,标题为 `yt-dlp test video`,ID 为 `BaW_jenozKc`,这将创建一个 `yt-dlp test video-BaW_jenozKc.mp4` 文件,创建在当前目录。 **注意**:某些序列可能不存在,因为它们依赖于特定提取器获取的元数据。此类序列将被占位符值替换(由 `--output-na-placeholder` 提供,默认为 `NA`)。 **提示**:使用 `-j` 查看特定 URL 的可用字段。 对于数字序列,可以使用 [数字相关格式化](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting);例如 `%(view_count)05d` 将生成一个字符串,其中观看次数用零填充到 5 位,例如 `00042`。 输出模板也可以包含任意层次路径;例如 `-o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s"` 将导致每个视频下载到对应路径模板创建的目录中。任何缺失的目录都会自动为你创建。 要使用输出模板中的百分文字面量,请使用 `%%`。要输出到标准输出,请使用 `-o -`。 当前默认模板为 `%(title)s [%(id)s].%(ext)s`。 在某些情况下,你不希望特殊字符(如中文、空格或 &)出现在文件名中,例如在将下载的文件传输到 Windows 系统或通过 8 位不安全通道传输文件名时。在这种情况下,添加 `--restrict-filenames` 标志以获得更短的文件名。 #### 输出模板示例 ``` $ yt-dlp --print filename -o "test video.%(ext)s" BaW_jenozKc test video.webm # Literal name with correct extension $ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc youtube-dl test video ''_ä↭𝕐.webm # All kinds of weird characters $ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc --restrict-filenames youtube-dl_test_video_.webm # Restricted file name # Download YouTube playlist videos in separate directory indexed by video order in a playlist $ yt-dlp -o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re" # Download YouTube playlist videos in separate directories according to their uploaded year $ yt-dlp -o "%(upload_date>%Y)s/%(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re" # Prefix playlist index with " - " separator, but only if it is available $ yt-dlp -o "%(playlist_index&{} - |)s%(title)s.%(ext)s" BaW_jenozKc "https://www.youtube.com/user/TheLinuxFoundation/playlists" # Download all playlists of YouTube channel/user keeping each playlist in separate directory: $ yt-dlp -o "%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/user/TheLinuxFoundation/playlists" # Download Udemy course keeping each chapter in separate directory under MyVideos directory in your home $ yt-dlp -u user -p password -P "~/MyVideos" -o "%(playlist)s/%(chapter_number)s - %(chapter)s/%(title)s.%(ext)s" "https://www.udemy.com/java-tutorial" # Download entire series season keeping each series and each season in separate directory under C:/MyVideos $ yt-dlp -P "C:/MyVideos" -o "%(series)s/%(season_number)s - %(season)s/%(episode_number)s - %(episode)s.%(ext)s" "https://videomore.ru/kino_v_detalayah/5_sezon/367617" # Download video as "C:\MyVideos\uploader\title.ext", subtitles as "C:\MyVideos\subs\uploader\title.ext" # and put all temporary files in "C:\MyVideos\tmp" $ yt-dlp -P "C:/MyVideos" -P "temp:tmp" -P "subtitle:subs" -o "%(uploader)s/%(title)s.%(ext)s" BaW_jenozKc --write-subs # Download video as "C:\MyVideos\uploader\title.ext" and subtitles as "C:\MyVideos\uploader\subs\title.ext" $ yt-dlp -P "C:/MyVideos" -o "%(uploader)s/%(title)s.%(ext)s" -o "subtitle:%(uploader)s/subs/%(title)s.%(ext)s" BaW_jenozKc --write-subs # Stream the video being downloaded to stdout $ yt-dlp -o - BaW_jenozKc ``` # 格式选择 默认情况下,yt-dlp 尝试下载最佳可用质量,如果你**不**传递任何选项。 这通常等同于使用 `-f bestvideo*+bestaudio/best`。然而,如果启用了多音频流(`--audio-multistreams`),默认格式会变为 `-f bestvideo+bestaudio/best`。类似地,如果 ffmpeg 不可用,或你使用 yt-dlp 流式传输到 `stdout`(`-o -`),默认格式变为 `-f best/bestvideo+bestaudio`。 **弃用警告**:最新版本的 yt-dlp 可以同时将多个格式流式传输到标准输出,使用 ffmpeg。因此,未来版本中,默认值将设置为 `-f bv*+ba/b`,类似于普通下载。如果希望保留 `-f b/bv+ba` 设置,建议在配置选项中明确指定。 格式选择的一般语法是 `-f FORMAT`(或 `--format FORMAT`),其中 `FORMAT` 是一个 *选择器表达式*,即描述你希望下载的格式或格式的表达式。 **简述**:[导航到示例](#format-selection-examples)。 最简单的场景是请求特定格式;例如使用 `-f 22` 可以下载格式代码等于 22 的格式。你可以使用 `--list-formats` 或 `-F` 获取特定视频的可用格式代码列表。请注意,这些格式代码是提取器特定的。 你也可以使用文件扩展名(当前支持 `3gp`、`aac`、`flv`、`m4a`、`mp3`、`mp4`、`ogg`、`wav`、`webm`)来下载特定扩展名的最佳质量格式作为单个文件,例如 `-f webm` 将下载最佳质量格式且扩展名为 `webm` 的单个文件。 你可以使用 `-f -` 交互式地为每个视频提供格式选择器。 你还可以使用特殊名称来选择特定边缘情况格式: - `all`:选择**所有格式**单独 - `mergeall`:选择并**合并所有格式**(必须与 `--audio-multistreams`、`--video-multistreams` 或两者一起使用) - `b*`、`best*`:选择最佳质量格式,**包含**视频或音频或两者(即 `vcodec!=none or acodec!=none`) - `b`、`best`:选择最佳质量格式,**同时包含**视频和音频。相当于 `best*[vcodec!=none][acodec!=none]` - `bv`、`bestvideo`:选择最佳质量**仅视频**格式。相当于 `best*[acodec=none]` - `bv*`、`bestvideo*`:选择最佳质量**包含视频**的格式。它可能也包含音频。相当于 `best*[vcodec!=none]` - `ba`、`bestaudio`:选择最佳质量**仅音频**格式。相当于 `best*[vcodec=none]` - `ba*`、`bestaudio*`:选择最佳质量**包含音频**的格式。它可能也包含视频。相当于 `best*[acodec!=none]`(**不推荐使用**) - `w*`、`worst*`:选择最差质量格式,**包含**视频或音频 - `w`、`worst`:选择最差质量格式,**同时包含**视频和音频。相当于 `worst*[vcodec!=none][acodec!=none]` - `wv`、`worstvideo`:选择最差质量**仅视频**格式。相当于 `worst*[acodec=none]` - `wv*`、`worstvideo*`:选择最差质量**包含视频**的格式。它可能也包含音频。相当于 `worst*[vcodec!=none]` - `wa`、`worstaudio`:选择最差质量**仅音频**格式。相当于 `worst*[vcodec=none]` - `wa*`、`worstaudio*`:选择最差质量**包含音频**的格式。它可能也包含视频。相当于 `worst*[acodec!=none]` 例如,要下载最差的视频仅格式,可以使用 `-f worstvideo`。不过,不推荐使用 `worst` 和相关选项。当格式选择器为 `worst` 时,会选择所有方面最差的格式。通常你实际想要的是文件最小的视频。因此,通常更推荐使用 `-S +size` 或更严谨地 `-S +size,+br,+res,+fps` 替代 `-f worst`。详见 [格式排序](#sorting-formats)。 你可以通过使用 `best.` 选择某类型下的第 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 ++...` 合并视频和音频的格式(需要安装 ffmpeg);例如 `-f bestvideo+bestaudio` 将下载最佳视频仅格式、最佳音频仅格式,并使用 ffmpeg 合并它们。 **弃用警告**:由于以下描述的行为复杂且反直觉,此行为将被移除,多流支持将默认启用。新的操作符将添加以限制格式为单音频/视频流 除非使用 `--video-multistreams`,否则所有包含视频流的格式(除了第一个)将被忽略。类似地,除非使用 `--audio-multistreams`,否则所有包含音频流的格式(除了第一个)将被忽略。例如,`-f bestvideo+best+bestaudio --video-multistreams --audio-multistreams` 将下载并合并所有 3 个给定格式。结果文件将包含 2 个视频流和 2 个音频流。但 `-f bestvideo+best+bestaudio --no-video-multistreams` 将仅下载并合并 `bestvideo` 和 `bestaudio`。`best` 将被忽略,因为已选择了包含视频流的格式(`bestvideo`)。格式顺序很重要:`-f best+bestaudio --no-audio-multistreams` 将仅下载 `best`,而 `-f bestaudio+best --no-audio-multistreams` 将忽略 `best` 并仅下载 `bestaudio`。 ## 格式过滤 你也可以通过使用括号中的条件来过滤视频格式,例如 `-f "best[height=720]"`(或 `-f "[filesize>10M]"` 因为没有选择器时会被解释为 `best`)。 以下数字元字段可用于比较 `<`、`<=`、`>`、`>=`、`=`(等于)、`!=`(不等于): - `filesize`:字节数,如果提前已知 - `filesize_approx`:字节数的估计值 - `width`:视频宽度,如果已知 - `height`:视频高度,如果已知 - `aspect_ratio`:视频宽高比,如果已知 - `tbr`:音频和视频的平均比特率(kbps) - `abr`:平均音频比特率(kbps) - `vbr`:平均视频比特率(kbps) - `asr`:音频采样率(Hz) - `fps`:帧速率 - `audio_channels`:音频通道数 - `stretched_ratio`:视频像素的宽高比(如果不是正方形) 字符串元字段也可以用于过滤: - `url`:视频 URL - `ext`:文件扩展名 - `acodec`:使用的音频编解码器 - `vcodec`:使用的视频编解码器 - `container`:容器格式名称 - `protocol`:用于实际下载的协议(小写)(`http`、`https`、`rtsp`、`rtmp`、`rtmpe`、`mms`、`f4m`、`ism`、`http_dash_segments`、`m3u8`、`m3u8_native`) - `language`:语言代码 - `dynamic_range`:视频的动态范围 - `format_id`:格式的简短描述 - `format`:人类可读的格式描述 - `format_note`:关于格式的附加信息 - `resolution`:宽度和高度的文本描述 任何字符串比较都可以通过前缀 `!` 进行否定,以产生相反的比较,例如 `!*=`(不包含)。比较的字符串值需要用单引号或双引号括起来,如果包含空格或特殊字符(除了 `._-`)。 **注意**:上述元字段并非保证存在,因为这完全取决于特定提取器提供的元数据,即网站提供的元数据。任何其他由提取器提供的字段也可以用于过滤。 如果某个字段的值未知,则会排除该格式,除非你在操作符后添加 `?`。你可以组合格式过滤器,例如 `-f "bv[height<=?720][tbr>500]"` 会选择高度不超过 720p(或高度未知)且比特率至少为 500 kbps 的视频格式。你也可以使用带有 `all` 的过滤器来下载所有满足条件的格式,例如 `-f "all[vcodec=none]"` 会下载所有仅音频的格式。 格式选择器也可以使用括号进行分组;例如 `-f "(mp4,webm)[height<480]"` 将下载最大高度小于 480 的最佳预合并 mp4 和 webm 格式。 ## 格式排序 你可以使用 `-S`(`--format-sort`)更改被视为“最佳”的标准。格式为 `--format-sort field1,field2...`。 可用字段包括: - `hasvid`:优先选择包含视频流的格式 - `hasaud`:优先选择包含音频流的格式 - `ie_pref`:格式偏好 - `lang`:语言偏好(由提取器确定,例如原始语言优先于音频描述) - `quality`:格式质量 - `source`:来源偏好 - `proto`:下载协议(`https`/`ftps` > `http`/`ftp` > `m3u8_native`/`m3u8` > `http_dash_segments` > `websocket_frag` > `mms`/`rtsp` > `f4f`/`f4m`) - `vcodec`:视频编解码器(`av01` > `vp9.2` > `vp9` > `h265` > `h264` > `vp8` > `h263` > `theora` > 其他) - `acodec`:音频编解码器(`flac`/`alac` > `wav`/`aiff` > `opus` > `vorbis` > `aac` > `mp4a` > `mp3` > `ac4` > `eac3` > `ac3` > `dts` > 其他) - `codec`:等效于 `vcodec,acodec` - `vext`:视频扩展名(`mp4` > `mov` > `webm` > `flv` > 其他)。如果使用 `--prefer-free-formats`,则 `webm` 优先 - `aext`:音频扩展名(`m4a` > `aac` > `mp3` > `ogg` > `opus` > `webm` > 其他)。如果使用 `--prefer-free-formats`,则顺序变为 `ogg` > `opus` > `webm` > `mp3` > `m4a` > `aac` - `ext`:等效于 `vext,aext` - `filesize`:精确文件大小,如果提前已知 - `fs_approx`:近似文件大小 - `size`:精确文件大小(如果可用),否则为近似文件大小 - `height`:视频高度 - `width`:视频宽度 - `res`:视频分辨率,计算为最小维度 - `fps`:视频帧速率 - `hdr`:视频的动态范围(`DV` > `HDR12` > `HDR10+` > `HDR10` > `HLG` > `SDR`) - `channels`:音频通道数 - `tbr`:总平均比特率(kbps) - `vbr`:平均视频比特率(kbps) - `abr`:平均音频比特率(ps) - `br`:平均比特率(kbps),`tbr`/`vbr`/`abr` - `asr`:音频采样率(Hz) **弃用警告**:许多这些字段有(目前未记录的)别名,可能在将来的版本中移除。建议仅使用文档中记录的字段名。 所有字段默认按降序排序。要反转顺序,请在该字段前加 `+`。例如 `+res` 优先选择分辨率最小的格式。此外,可以为字段指定首选值,用 `:` 分隔。例如 `res:720` 优先选择分辨率不超过 720p 的视频,且在没有小于 720p 的视频时选择最小的视频。如果对 `codec` 和 `ext` 指定两个首选值,第一个用于视频,第二个用于音频。例如 `+codec:avc:m4a`(等价于 `+vcodec:avc,+acodec:m4a`)设置视频编解码器偏好为 `h264` > `h265` > `vp9` > `vp9.2` > `av01` > `vp8` > `h263` > `theora`,音频编解码器偏好为 `mp4a` > `aac` > `vorbis` > `opus` > `mp3` > `ac3` > `dts`。你也可以使用 `~` 作为分隔符来指定接近的值。例如 `filesize~1G` 优先选择文件大小最接近 1 GiB 的格式。 字段 `hasvid` 和 `ie_pref` 始终被赋予最高优先级,无论用户定义的顺序如何。此行为可以通过使用 `--format-sort-force` 更改。除了这些之外,默认顺序为:`lang,quality,res,fps,hdr:12,vcodec,channels,acodec,size,br,asr,proto,ext,hasaud,source,id`。提取器可以覆盖此默认顺序,但不能覆盖用户提供的顺序。 注意:默认的 `hdr` 为 `hdr:12`;即不优先选择 Dolby Vision。此选择是因为 DV 格式尚未完全兼容大多数设备。未来可能会更改。 如果格式选择器为 `worst`,则在排序后选择最后一项。这意味着它会选择所有方面最差的格式。大多数时候,你实际想要的是文件大小最小的视频。因此,通常更推荐使用 `-f best -S +size,+br,+res,+fps`。 如果你多次使用 `-S`/`--format-sort`,每个后续排序参数将前置到前一个参数中,并且仅保留任何重复字段的最高优先级。例如,`-S proto -S res` 等价于 `-S res,proto`,而 `-S res:720,fps -S vcodec,res:1080` 等价于 `-S vcodec,res:1080,fps`。你可以使用 `--format-sort-reset` 忽略任何先前传递的 `-S`/`--format-sort` 参数并重置为默认顺序。 **提示**:你可以使用 `-v -F` 查看格式排序方式(从最差到最佳)。 ## 格式选择示例 ``` # Download and merge the best video-only format and the best audio-only format, # or download the best combined format if video-only format is not available $ yt-dlp -f "bv+ba/b" # Download best format that contains video, # and if it doesn't already have an audio stream, merge it with best audio-only format $ yt-dlp -f "bv*+ba/b" # Same as above $ yt-dlp # Download the best video-only format and the best audio-only format without merging them # For this case, an output template should be used since # by default, bestvideo and bestaudio will have the same file name. $ yt-dlp -f "bv,ba" -o "%(title)s.f%(format_id)s.%(ext)s" # Download and merge the best format that has a video stream, # and all audio-only formats into one file $ yt-dlp -f "bv*+mergeall[vcodec=none]" --audio-multistreams # Download and merge the best format that has a video stream, # and the best 2 audio-only formats into one file $ yt-dlp -f "bv*+ba+ba.2" --audio-multistreams # The following examples show the old method (without -S) of format selection # and how to use -S to achieve a similar but (generally) better result # Download the worst video available (old method) $ yt-dlp -f "wv*+wa/w" # Download the best video available but with the smallest resolution $ yt-dlp -S "+res" # Download the smallest video available $ yt-dlp -S "+size,+br" # Download the best mp4 video available, or the best video if no mp4 available $ yt-dlp -f "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4] / bv*+ba/b" # Download the best video with the best extension # (For video, mp4 > mov > webm > flv. For audio, m4a > aac > mp3 ...) $ yt-dlp -S "ext" # Download the best video available but no better than 480p, # or the worst video if there is no video under 480p $ yt-dlp -f "bv*[height<=480]+ba/b[height<=480] / wv*+ba/w" # Download the best video available with the largest height but no better than 480p, # or the best video with the smallest resolution if there is no video under 480p $ yt-dlp -S "height:480" # Download the best video available with the largest resolution but no better than 480p, # or the best video with the smallest resolution if there is no video under 480p # Resolution is determined by using the smallest dimension. # So this works correctly for vertical videos as well $ yt-dlp -S "res:480" # Download the best video (that also has audio) but no bigger than 50 MB, # or the worst video (that also has audio) if there is no video under 50 MB $ yt-dlp -f "b[filesize<50M] / w" # Download the largest video (that also has audio) but no bigger than 50 MB, # or the smallest video (that also has audio) if there is no video under 50 MB $ yt-dlp -f "b" -S "filesize:50M" # Download the best video (that also has audio) that is closest in size to 50 MB $ yt-dlp -f "b" -S "filesize~50M" # Download best video available via direct link over HTTP/HTTPS protocol, # or the best video available via any protocol if there is no such video $ yt-dlp -f "(bv*+ba/b)[protocol^=http][protocol!*=dash] / (bv*+ba/b)" # Download best video available via the best protocol # (https/ftps > http/ftp > m3u8_native > m3u8 > http_dash_segments ...) $ yt-dlp -S "proto" # Download the best video with either h264 or h265 codec, # or the best video if there is no such video $ yt-dlp -f "(bv*[vcodec~='^((he|a)vc|h26[45])']+ba) / (bv*+ba/b)" # Download the best video with best codec no better than h264, # or the best video with worst codec if there is no such video $ yt-dlp -S "codec:h264" # Download the best video with worst codec no worse than h264, # or the best video with best codec if there is no such video $ yt-dlp -S "+codec:h264" # More complex examples # Download the best video no better than 720p preferring framerate greater than 30, # or the worst video (still preferring framerate greater than 30) if there is no such video $ yt-dlp -f "((bv*[fps>30]/bv*)[height<=720]/(wv*[fps>30]/wv*)) + ba / (b[fps>30]/b)[height<=720]/(w[fps>30]/w)" # Download the video with the largest resolution no better than 720p, # or the video with the smallest resolution available if there is no such video, # preferring larger framerate for formats with the same resolution $ yt-dlp -S "res:720,fps" # Download the video with smallest resolution no worse than 480p, # or the video with the largest resolution available if there is no such video, # preferring better codec and then larger total bitrate for the same resolution $ yt-dlp -S "+res:480,codec,br" ``` # 修改元数据 通过 `--parse-metadata` 和 `--replace-in-metadata` 可以修改获取的元数据。 `--replace-in-metadata FIELDS REGEX REPLACE` 用于使用 [Python 正则表达式](https://docs.python.org/3/library/re.html) 替换任何元数据字段中的文本。[反向引用](https://docs.python.org/3/library/re.html#re.sub) 可用于高级用途。 `--parse-metadata FROM:TO` 的通用语法是给出要从中提取数据的字段或 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax),以及要解释为的格式,用冒号 `:` 分隔。可以使用 [Python 正则表达式](https://docs.python.org/3/library/re.html)(带命名捕获组)、单个字段名,或类似 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax) 的语法(仅支持 `%(field)s` 格式)用于 `TO`。该选项可以多次使用以解析和修改各种字段。 注意这些选项保留其相对顺序,允许在解析字段后进行替换,反之亦然。此外,由此创建的任何字段都可用于 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax) 并影响使用 `--embed-metadata` 添加到媒体文件的元数据。 此选项还有几个特殊用途: * 你可以下载一个额外的 URL,基于当前下载视频的元数据。要实现这一点,将字段 `additional_urls` 设置为要下载的 URL。例如 `--parse-metadata "description:(?Phttps?://www\.vimeo\.com/\d+)"` 将下载描述中第一个找到的 vimeo 视频 * 你可以使用此选项修改嵌入媒体文件中的元数据。为此,将对应字段的值设置为带有 `meta_` 前缀的值。例如,任何设置到 `meta_description` 字段的值将添加到文件的 `description` 字段中——你可以使用此功能设置不同的“描述”和“概要”。要修改各个流的元数据,请使用 `meta_` 前缀(例如 `meta1_language`)。任何设置到 `meta_` 字段的值将覆盖所有默认值。 **注意**:元数据修改发生在格式选择、提取后和其他后处理操作之前。某些字段可能会在此步骤中添加或更改,从而覆盖你的更改。 默认情况下,yt-dlp 会向文件添加以下元数据: 元数据字段 | 来源 :----------|:------------------------------------------------ `title` | `track` 或 `title` `date` | `upload_date` `description`, `synopsis` | `description` `purl`, `comment` | `webpage_url` `track` | `track_number` `artist` | `artist`, `artists`, `creator`, `creators`, `uploader` 或 `uploader_id` `composer` | `composer` 或 `composers` `genre` | `genre`, `genres`, `categories` 或 `tags` `album` | `album` 或 `series` `album_artist` | `album_artist` 或 `album_artists` `disc` | `disc_number` `show` | `series` `season_number` | `season_number` `episode_id` | `episode` 或 `episode_id` `episode_sort` | `episode_number` `language` of each stream | 该格式的 `language` **注意**:文件格式可能不支持这些字段 ## 修改元数据示例 ``` # Interpret the title as "Artist - Title" $ yt-dlp --parse-metadata "title:%(artist)s - %(title)s" # Regex example $ yt-dlp --parse-metadata "description:Artist - (?P.+)" # Copy the episode field to the title field (with FROM and TO as single fields) $ yt-dlp --parse-metadata "episode:title" # Set title as "Series name S01E05" $ yt-dlp --parse-metadata "%(series)s S%(season_number)02dE%(episode_number)02d:%(title)s" # Prioritize uploader as the "artist" field in video metadata $ yt-dlp --parse-metadata "%(uploader|)s:%(meta_artist)s" --embed-metadata # Set "comment" field in video metadata using description instead of webpage_url, # handling multiple lines correctly $ yt-dlp --parse-metadata "description:(?s)(?P.+)" --embed-metadata # Do not set any "synopsis" in the video metadata $ yt-dlp --parse-metadata ":(?P)" # Remove "formats" field from the infojson by setting it to an empty string $ yt-dlp --parse-metadata "video::(?P)" --write-info-json # Replace all spaces and "_" in title and uploader with a `-` $ yt-dlp --replace-in-metadata "title,uploader" "[ _]" "-" ``` # 提取器参数 某些提取器接受可通过 `--extractor-args KEY:ARGS` 传递的附加参数。`ARGS` 是以 `;`(分号)分隔的 `ARG=VAL1,VAL2` 字符串。例如 `--extractor-args "youtube:player-client=tv,mweb;formats=incomplete" --extractor-args "twitter:api=syndication"` **注意**:在 CLI 中,`ARG` 可以使用 `-` 替代 `_`;例如 `youtube:player-client"` 变为 `youtube:player_client"` 以下提取器使用此功能: #### youtube * `lang`:优先使用此语言代码(区分大小写)翻译的元数据(`title`、`description` 等)。默认优先使用视频主要语言元数据,并回退到 `en` 翻译。参见 [youtube/_base.py](https://github.com/yt-dlp/yt-dlp/blob/master/youtube/_base.py) 获取支持的内容语言代码列表 * `skip`:一个或多个 `hls`、`dash` 或 `translated_subs`,用于跳过提取 m3u8 清单、dash 清单和 [自动翻译字幕](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/blob/master/docs/Subtitle.md#auto-translated-subtitles) 分别。有关详细信息,请参见 [#860](https://github.com/yt-dlp/yt-dlp/issues/860) 和 [#12826](https://github.com/yt-dlp/yt-dlp/issues/12826) * `player_client`:用于提取视频数据的客户端支持的客户端有 `web`、`web_safari`、`web_embedded`、`web_music`、`web_creator`、`mweb`、`ios`、`android`、`android_vr`、`tv`、`tv_downgraded` 和 `tv_simply`。默认情况下,`android_vr,web_safari` 被使用。如果未安装 JavaScript 运行时/引擎,则仅使用 `android_vr`。如果登录了 Cookie,则 `tv_downgraded,web_safari` 用于免费账户,`tv_downgraded,web_creator` 用于高级账户。`web_music` 会在访问 music.youtube.com 时添加(登录 Cookie)。`web_embedded` 会在访问年龄限制视频时添加,但仅在某些情况下有效(如果视频可嵌入),并且可能作为回退添加如果 `android_vr` 无法访问视频。`web_creator` 会在需要账户年龄验证时添加。一些客户端(如 `web_creator` 和 `web_music`)需要 `po_token` 才能下载其格式。某些客户端(如 `web_creator`)仅在使用认证时有效。并非所有客户端都支持通过 Cookie 进行认证。可以使用 `default` 表示默认客户端,或使用 `all` 表示所有客户端(不推荐)。你可以通过在客户端前加 `-` 来排除它,例如 `youtube:player_client=default,-web_safari` * `player_skip`:跳过一些通常需要的网络请求以实现稳健提取。可选值包括 `configs`(跳过客户端配置)、`webpage`(跳过初始网页)、`js`(跳过 JavaScript 播放器)、`initial_data`(跳过初始数据/下一个请求)。虽然这些选项可以减少请求数量或避免某些速率限制,但可能导致格式缺失或元数据错误。详见 [#860](https://github.com/yt-dlp/yt-dlp/issues/860) 和 [#12826](https://github.com/yt-dlp/yt-dlp/issues/12826) * `webpage_skip`:跳过提取嵌入的网页数据。可选值包括 `player_response` 和 `initial_data`。这些选项用于测试,不会跳过任何网络请求。默认不会跳过任何选项;但如果使用了 `player_js_version` 的非 `actual` 值,则隐含 `webpage_skip=player_response` * `webpage_client`:用于网页请求的客户端。选项为 `web` 或 `web_safari`(默认) * `player_params`:YouTube 播放器参数,将覆盖默认参数 * `player_js_variant`:用于 n/sig 解密的播放器 JavaScript 变体。已知变体包括:`main`、`tcc`、`tce`、`es5`、`es6`、`es6_tcc`、`es6_tce`、`tv`、`tv_es6`、`phone`、`house`。默认是 `main`,其他用于调试。你可以使用 `actual` 以使用站点规定的值 * `player_js_version`:用于 n/sig 解密的播放器 JavaScript 版本,格式为 `signature_timestamp@hash`(例如 `20348@0004de42`)。默认使用站点规定的版本,可通过 `actual` 选择。使用其他值将隐含 `webpage_skip=player_response` * `comment_sort`:`top` 或 `new`(默认)- 选择评论排序模式(YouTube 侧) * `max_comments`:限制获取的评论数量。逗号分隔的整数列表,表示 `max-comments,max-parents,max-replies,max-replies-per-thread,max-depth`。默认是 `all,all,all,all,all` * `max-depth` 为 `1` 将丢弃所有回复,无论 `max-replies` 或 `max-replies-per-thread` 的值如何 * 例如 `all,all,1000,10,2` 将获取最多 1000 条回复,每条线程最多 10 条回复,且仅 2 层深度(顶级评论及其直接回复)。`1000,all,100` 将获取最多 1000 条评论,最大 100 条回复 * `formats`:更改返回的格式类型。`dashy`(将 HTTP 转换为 DASH)、`duplicate`(内容相同但 URL 或协议不同的格式;包含 `dashy`)、`incomplete`(无法完整下载的直播 DASH、直播自适应 HTTPS 和直播 m3u8)、`missing_pot`(包含需要 PO Token 但缺失的格式) * `innertube_host`:用于所有 API 请求的 Innertube API 主机;例如 `studio.youtube.com`、`youtubei.googleapis.com`。注意从一个子域导出的 Cookie 不能用于其他子域 * `innertube_key`:用于所有 API 请求的 Innertube API 密钥。默认不使用 API 密钥 * `raise_incomplete_data`:`Incomplete Data Received` 抛出错误而不是报告警告 * `data_sync_id`:覆盖用于 Innertube API 请求的账户 Data Sync ID。这在使用 `youtube:player_skip=webpage,configs` 或 `youtubetab:skip=webpage` 时可能需要 * `visitor_data`:覆盖用于 Innertube API 请求的 Visitor Data。这应该与 `player_skip=webpage,configs` 一起使用,并且没有 Cookie。注意:不当使用可能产生不良影响。如果要从浏览器会话使用 Cookie,你应该传递 Cookie(它包含 Visitor ID) * `po_token`:证明来源(PO)令牌列表,格式为 `CLIENT.CONTEXT+PO_TOKEN`,例如 `youtube:po_token=web.gvs+XXX,web.player=XXX,web_safari.gvs+YYY`。上下文可以是 `gvs`(Google 视频服务器 URL)、`player`(Innertube 播放器请求)或 `subs`(字幕)。 * `pot_trace`:启用 PO Token 获取的调试日志记录。`true` 或 `false`(默认) * `fetch_pot`:用于获取 PO Token 的策略。`always`(始终尝试获取 PO Token,无论客户端是否需要)、`never`(从不获取)或 `auto`(默认;仅当客户端需要时获取) * `jsc_trace`:启用 JS 挑战获取的调试日志记录。`true` 或 `false`(默认) * `use_ad_playback_context`:跳过预滚广告以消除强制等待期。不要在向 yt-dlp 传递高级账户 Cookie 时使用此选项,否则会导致高级格式丢失。仅对 `mweb` 和 `web_music` 播放器客户端有效。`true` 或 `false`(默认) #### youtube-ejs * `jitless`:在受支持的 JavaScript 引擎中以无 JIT 模式运行。支持运行时:`deno`、`node` 和 `bun`。提供更好的安全性,但会降低性能/速度。注意 `node` 和 `bun` 仍被认为是不安全的。可以是 `true` 或 `false`(默认) #### youtubepot-webpo * `bind_to_visitor_id`:是否使用 Visitor ID 而非 Visitor Data 进行缓存。`true`(默认)或 `false` #### youtubetab(YouTube 播放列表、频道、订阅源等) * `skip`:一个或多个 `webpage`(跳过初始网页下载)、`authcheck`(允许在未下载初始网页时下载需要认证的播放列表。这可能导致意外行为,请参见 [#1122](https://github.com/yt-dlp/yt-dlp/issues/1122)) * `approximate_date`:提取近似的 `upload_date` 和 `timestamp`。这可能导致基于日期的筛选略有偏差 #### 通用 * `fragment_query`:如果未提供值,则将查询参数透传给 mpd/m3u8 片段 URL,否则应用给定的查询字符串。例如 `fragment_query=VALUE`。不适用于 ffmpeg * `variant_query`:如果未提供值,则将查询参数透传给主 m3u8 URL 的变体播放列表,否则应用给定的查询字符串。例如 `variant_query=VALUE`。不适用于 ffmpeg * `key_query`:如果未提供值,则将查询参数透传给主 m3u8 URL 的 HLS AES-128 解密密钥 URI,否则应用给定的查询字符串。例如 `key_query=VALUE`。不适用于 ffmpeg * `hls_key`:HLS AES-128 密钥 URI 或密钥(十六进制),可选地加上 IV(十六进制),格式为 `(URI|KEY)[,IV]`;例如 `generic:hls_key=ABCDEF1234567980,0xFEDCBA0987654321`。使用此选项将强制使用本地 HLS 下载器并覆盖 m3u8 播放列表中相应的 * `is_live`:绕过直播 HLS 检测并手动设置 `live_status` - 值 `false` 将设置为 `not_live`,其他值(或无值)将设置为 `is_live` # 使用与选项 ``` yt-dlp [OPTIONS] [--] URL [URL...] ``` 提示:使用 `CTRL`+`F`(或 `Command`+`F`)搜索关键词 ## 通用选项: ``` -h, --help Print this help text and exit --version Print program version and exit -U, --update Update this program to the latest version --no-update Do not check for updates (default) --update-to [CHANNEL]@[TAG] Upgrade/downgrade to a specific version. CHANNEL can be a repository as well. CHANNEL and TAG default to "stable" and "latest" respectively if omitted; See "UPDATE" for details. Supported channels: stable, nightly, master -i, --ignore-errors Ignore download and postprocessing errors. The download will be considered successful even if the postprocessing fails --no-abort-on-error Continue with next video on download errors; e.g. to skip unavailable videos in a playlist (default) --abort-on-error Abort downloading of further videos if an error occurs (Alias: --no-ignore-errors) --list-extractors List all supported extractors and exit --extractor-descriptions Output descriptions of all supported extractors and exit --use-extractors NAMES Extractor names to use separated by commas. You can also use regexes, "all", "default" and "end" (end URL matching); e.g. --ies "holodex.*,end,youtube". Prefix the name with a "-" to exclude it, e.g. --ies default,-generic. Use --list-extractors for a list of extractor names. (Alias: --ies) --default-search PREFIX Use this prefix for unqualified URLs. E.g. "gvsearch2:python" downloads two videos from google videos for the search term "python". Use the value "auto" to let yt-dlp guess ("auto_warning" to emit a warning when guessing). "error" just throws an error. The default value "fixup_error" repairs broken URLs, but emits an error if this is not possible instead of searching --ignore-config Don't load any more configuration files except those given to --config-locations. For backward compatibility, if this option is found inside the system configuration file, the user configuration is not loaded. (Alias: --no-config) --no-config-locations Do not load any custom configuration files (default). When given inside a configuration file, ignore all previous --config-locations defined in the current file --config-locations PATH Location of the main configuration file; either the path to the config or its containing directory ("-" for stdin). Can be used multiple times and inside other configuration files --plugin-dirs DIR Path to an additional directory to search for plugins. This option can be used multiple times to add multiple directories. Use "default" to search the default plugin directories (default) --no-plugin-dirs Clear plugin directories to search, including defaults and those provided by previous --plugin-dirs --js-runtimes RUNTIME[:PATH] Additional JavaScript runtime to enable, with an optional location for the runtime (either the path to the binary or its containing directory). This option can be used multiple times to enable multiple runtimes. Supported runtimes are (in order of priority, from highest to lowest): deno, node, quickjs, bun. Only "deno" is enabled by default. The highest priority runtime that is both enabled and available will be used. In order to use a lower priority runtime when "deno" is available, --no-js- runtimes needs to be passed before enabling other runtimes --no-js-runtimes Clear JavaScript runtimes to enable, including defaults and those provided by previous --js-runtimes --remote-components COMPONENT Remote components to allow yt-dlp to fetch when required. This option is currently not needed if you are using an official executable or have the requisite version of the yt-dlp-ejs package installed. You can use this option multiple times to allow multiple components. Supported values: ejs:npm (external JavaScript components from npm), ejs:github (external JavaScript components from yt-dlp-ejs GitHub). By default, no remote components are allowed --no-remote-components Disallow fetching of all remote components, including any previously allowed by --remote-components or defaults. --flat-playlist Do not extract a playlist's URL result entries; some entry metadata may be missing and downloading may be bypassed --no-flat-playlist Fully extract the videos of a playlist (default) --live-from-start Download livestreams from the start. Currently experimental and only supported for YouTube, Twitch, and TVer --no-live-from-start Download livestreams from the current time (default) --wait-for-video MIN[-MAX] Wait for scheduled streams to become available. Pass the minimum number of seconds (or range) to wait between retries --no-wait-for-video Do not wait for scheduled streams (default) --mark-watched Mark videos watched (even with --simulate) --no-mark-watched Do not mark videos watched (default) --color [STREAM:]POLICY Whether to emit color codes in output, optionally prefixed by the STREAM (stdout or stderr) to apply the setting to. Can be one of "always", "auto" (default), "never", or "no_color" (use non color terminal sequences). Use "auto-tty" or "no_color-tty" to decide based on terminal support only. Can be used multiple times --compat-options OPTS Options that can help keep compatibility with youtube-dl or youtube-dlc configurations by reverting some of the changes made in yt-dlp. See "Differences in default behavior" for details --alias ALIASES OPTIONS Create aliases for an option string. Unless an alias starts with a dash "-", it is prefixed with "--". Arguments are parsed according to the Python string formatting mini-language. E.g. --alias get-audio,-X "-S aext:{0},abr -x --audio-format {0}" creates options "--get-audio" and "-X" that takes an argument (ARG0) and expands to "-S aext:ARG0,abr -x --audio-format ARG0". All defined aliases are listed in the --help output. Alias options can trigger more aliases; so be careful to avoid defining recursive options. As a safety measure, each alias may be triggered a maximum of 100 times. This option can be used multiple times -t, --preset-alias PRESET Applies a predefined set of options. e.g. --preset-alias mp3. The following presets are available: mp3, aac, mp4, mkv, sleep. See the "Preset Aliases" section at the end for more info. This option can be used multiple times ``` ## 网络选项: ``` --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 --socket-timeout SECONDS Time to wait before giving up, in seconds --source-address IP Client-side IP address to bind to --impersonate CLIENT[:OS] Client to impersonate for requests. E.g. chrome, chrome-110, chrome:windows-10. Pass --impersonate="" to impersonate any client. Note that forcing impersonation for all requests may have a detrimental impact on download speed and stability --list-impersonate-targets List available clients to impersonate. -4, --force-ipv4 Make all connections via IPv4 -6, --force-ipv6 Make all connections via IPv6 --enable-file-urls Enable file:// URLs. This is disabled by default for security reasons. ``` ## 地理限制: ``` --geo-verification-proxy URL Use this proxy to verify the IP address for some geo-restricted sites. The default proxy specified by --proxy (or none, if the option is not present) is used for the actual downloading --xff VALUE How to fake X-Forwarded-For HTTP header to try bypassing geographic restriction. One of "default" (only when known to be useful), "never", an IP block in CIDR notation, or a two-letter ISO 3166-2 country code ``` ## 视频选择: ``` -I, --playlist-items ITEM_SPEC Comma-separated playlist_index of the items to download. You can specify a range using "[START]:[STOP][:STEP]". For backward compatibility, START-STOP is also supported. Use negative indices to count from the right and negative STEP to download in reverse order. E.g. "-I 1:3,7,-5::2" used on a playlist of size 15 will download the items at index 1,2,3,7,11,13,15 --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 --date DATE Download only videos uploaded on this date. The date can be "YYYYMMDD" or in the format [now|today|yesterday][-N[day|week|month|year]]. E.g. "--date today-2weeks" downloads only videos uploaded on the same day two weeks ago --datebefore DATE Download only videos uploaded on or before this date. The date formats accepted are the same as --date --dateafter DATE Download only videos uploaded on or after this date. The date formats accepted are the same as --date --match-filters FILTER Generic video filter. Any "OUTPUT TEMPLATE" field can be compared with a number or a string using the operators defined in "Filtering Formats". You can also simply specify a field to match if the field is present, use "!field" to check if the field is not present, and "&" to check multiple conditions. Use a "\" to escape "&" or quotes if needed. If used multiple times, the filter matches if at least one of the conditions is met. E.g. --match-filters !is_live --match-filters "like_count>?100 & description~='(?i)\bcats \& dogs\b'" matches only videos that are not live OR those that have a like count more than 100 (or the like field is not available) and also has a description that contains the phrase "cats & dogs" (caseless). Use "--match-filters -" to interactively ask whether to download each video --no-match-filters Do not use any --match-filters (default) --break-match-filters FILTER Same as "--match-filters" but stops the download process when a video is rejected --no-break-match-filters Do not use any --break-match-filters (default) --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 --age-limit YEARS Download only videos suitable for the given age --download-archive FILE Download only videos not listed in the archive file. Record the IDs of all downloaded videos in it --no-download-archive Do not use archive file (default) --max-downloads NUMBER Abort after downloading NUMBER files --break-on-existing Stop the download process when encountering a file that is in the archive supplied with the --download-archive option --no-break-on-existing Do not stop the download process when encountering a file that is in the archive (default) --break-per-input Alters --max-downloads, --break-on-existing, --break-match-filters, and autonumber to reset per input URL --no-break-per-input --break-on-existing and similar options terminates the entire download queue --skip-playlist-after-errors N Number of allowed failures until the rest of the playlist is skipped ``` ## 下载选项: ``` -N, --concurrent-fragments N Number of fragments of a dash/hlsnative video that should be downloaded concurrently (default is 1) -r, --limit-rate RATE Maximum download rate in bytes per second, e.g. 50K or 4.2M --throttled-rate RATE Minimum download rate in bytes per second below which throttling is assumed and the video data is re-extracted, e.g. 100K -R, --retries RETRIES Number of retries (default is 10), or "infinite" --file-access-retries RETRIES Number of times to retry on file access error (default is 3), or "infinite" --fragment-retries RETRIES Number of retries for a fragment (default is 10), or "infinite" (DASH, hlsnative and ISM) --retry-sleep [TYPE:]EXPR Time to sleep between retries in seconds (optionally) prefixed by the type of retry (http (default), fragment, file_access, extractor) to apply the sleep to. EXPR can be a number, linear=START[:END[:STEP=1]] or exp=START[:END[:BASE=2]]. This option can be used multiple times to set the sleep for the different retry types, e.g. --retry-sleep linear=1::2 --retry-sleep fragment:exp=1:20 --skip-unavailable-fragments Skip unavailable fragments for DASH, hlsnative and ISM downloads (default) (Alias: --no-abort-on-unavailable-fragments) --abort-on-unavailable-fragments Abort download if a fragment is unavailable (Alias: --no-skip-unavailable-fragments) --keep-fragments Keep downloaded fragments on disk after downloading is finished --no-keep-fragments Delete downloaded fragments after downloading is finished (default) --buffer-size SIZE Size of download buffer, e.g. 1024 or 16K (default is 1024) --resize-buffer The buffer size is automatically resized from an initial value of --buffer-size (default) --no-resize-buffer Do not automatically adjust the buffer size --http-chunk-size SIZE Size of a chunk for chunk-based HTTP downloading, e.g. 10485760 or 10M (default is disabled). May be useful for bypassing bandwidth throttling imposed by a webserver (experimental) --playlist-random Download playlist videos in random order --lazy-playlist Process entries in the playlist as they are received. This disables n_entries, --playlist-random and --playlist-reverse --no-lazy-playlist Process videos in the playlist only after the entire playlist is parsed (default) --hls-use-mpegts Use the mpegts container for HLS videos; allowing some players to play the video while downloading, and reducing the chance of file corruption if download is interrupted. This is enabled by default for live streams --no-hls-use-mpegts Do not use the mpegts container for HLS videos. This is default when not downloading live streams --download-sections REGEX Download only chapters that match the regular expression. A "*" prefix denotes time-range instead of chapter. Negative timestamps are calculated from the end. "*from-url" can be used to download between the "start_time" and "end_time" extracted from the URL. Needs ffmpeg. This option can be used multiple times to download multiple sections, e.g. --download-sections "*10:15-inf" --download-sections "intro" --downloader [PROTO:]NAME Name or path of the external downloader to use (optionally) prefixed by the protocols (http, ftp, m3u8, dash, rstp, rtmp, mms) to use it for. Currently supports native, aria2c, axel, curl, ffmpeg, httpie, wget. You can use this option multiple times to set different downloaders for different protocols. E.g. --downloader aria2c --downloader "dash,m3u8:native" will use aria2c for http/ftp downloads, and the native downloader for dash/m3u8 downloads (Alias: --external-downloader) --downloader-args NAME:ARGS Give these arguments to the external downloader. Specify the downloader name and the arguments separated by a colon ":". For ffmpeg, arguments can be passed to different positions using the same syntax as --postprocessor-args. You can use this option multiple times to give different arguments to different downloaders (Alias: --external-downloader-args) ``` ## 文件系统选项: ``` -a, --batch-file FILE File containing URLs to download ("-" for stdin), one URL per line. Lines starting with "#", ";" or "]" are considered as comments and ignored --no-batch-file Do not read URLs from batch file (default) -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") --restrict-filenames Restrict filenames to only ASCII characters, and avoid "&" and spaces in filenames --no-restrict-filenames Allow Unicode characters, "&" and spaces in filenames (default) --windows-filenames Force filenames to be Windows-compatible --no-windows-filenames Sanitize filenames only minimally --trim-filenames LENGTH Limit the filename length (excluding extension) to the specified number of characters -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 --no-mtime Do not use the Last-modified header to set the file modification time (default) --write-description Write video description to a .description file --no-write-description Do not write video description (default) --write-info-json Write video metadata to a .info.json file (this may contain personal information) --no-write-info-json Do not write video metadata (default) --write-playlist-metafiles Write playlist metadata in addition to the video metadata when using --write-info-json, --write-description etc. (default) --no-write-playlist-metafiles Do not write playlist metadata when using --write-info-json, --write-description etc. --clean-info-json Remove some internal metadata such as filenames from the infojson (default) --no-clean-info-json Write all fields to the infojson --write-comments Retrieve video comments to be placed in the infojson. The comments are fetched even without this option if the extraction is known to be quick (Alias: --get-comments) --no-write-comments Do not retrieve video comments unless the extraction is known to be quick (Alias: --no-get-comments) --load-info-json FILE JSON file containing the video information (created with the "--write-info-json" option) --cookies FILE Netscape formatted file to read cookies from and dump cookie jar in --no-cookies Do not read/dump cookies from/to file (default) --cookies-from-browser BROWSER[+KEYRING][:PROFILE][::CONTAINER] The name of the browser to load cookies from. Currently supported browsers are: brave, chrome, chromium, edge, firefox, opera, safari, vivaldi, whale. Optionally, the KEYRING used for decrypting Chromium cookies on Linux, the name/path of the PROFILE to load cookies from, and the CONTAINER name (if Firefox) ("none" for no container) can be given with their respective separators. By default, all containers of the most recently accessed profile are used. Currently supported keyrings are: basictext, gnomekeyring, kwallet, kwallet5, kwallet6 --no-cookies-from-browser Do not load cookies from browser (default) --cache-dir DIR Location in the filesystem where yt-dlp can store some downloaded information (such as client ids and signatures) permanently. By default ${XDG_CACHE_HOME}/yt-dlp --no-cache-dir Disable filesystem caching --rm-cache-dir Delete all filesystem cache files ``` ## 缩略图选项: ``` --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 快捷方式选项: ``` --write-link Write an internet shortcut file, depending on the current platform (.url, .webloc or .desktop). The URL may be cached by the OS --write-url-link Write a .url Windows internet shortcut. The OS caches the URL based on the file path --write-webloc-link Write a .webloc macOS internet shortcut --write-desktop-link Write a .desktop Linux internet shortcut ``` ## 详细信息和模拟选项: ``` -q, --quiet Activate quiet mode. If used with --verbose, print the log to stderr --no-quiet Deactivate quiet mode. (Default) --no-warnings Ignore warnings -s, --simulate Do not download the video and do not write anything to disk --no-simulate Download the video even if printing/listing options are used --ignore-no-formats-error Ignore "No video formats" error. Useful for extracting metadata even if the videos are not actually available for download (experimental) --no-ignore-no-formats-error Throw error when no downloadable video formats are found (default) --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 --print-to-file [WHEN:]TEMPLATE FILE Append given template to the file. The values of WHEN and TEMPLATE are the same as that of --print. FILE uses the same syntax as the output template. This option can be used multiple times -j, --dump-json Quiet, but print JSON information for each video. Simulate unless --no-simulate is used. See "OUTPUT TEMPLATE" for a description of available keys -J, --dump-single-json Quiet, but print JSON information for each URL or infojson passed. Simulate unless --no-simulate is used. If the URL refers to a playlist, the whole playlist information is dumped in a single line --force-write-archive Force download archive entries to be written as far as no errors occur, even if -s or another simulation option is used (Alias: --force-download-archive) --newline Output progress bar as new lines --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) -v, --verbose Print various debugging information --dump-pages Print downloaded pages encoded using base64 to debug problems (very verbose) --write-pages Write downloaded intermediary pages to files in the current directory to debug problems --print-traffic Display sent and read HTTP traffic ``` ## 修复措施: ``` --encoding ENCODING Force the specified encoding (experimental) --legacy-server-connect Explicitly allow HTTPS connection to servers that do not support RFC 5746 secure renegotiation --no-check-certificates Suppress HTTPS certificate validation --prefer-insecure Use an unencrypted connection to retrieve information about the video (Currently supported only for YouTube) --add-headers FIELD:VALUE Specify a custom HTTP header and its value, separated by a colon ":". You can use this option multiple times --bidi-workaround Work around terminals that lack bidirectional text support. Requires bidiv or fribidi executable in PATH --sleep-requests SECONDS Number of seconds to sleep between requests during data extraction --sleep-interval SECONDS Number of seconds to sleep before each download. This is the minimum time to sleep when used along with --max-sleep-interval (Alias: --min-sleep-interval) --max-sleep-interval SECONDS Maximum number of seconds to sleep. Can only be used along with --min-sleep-interval --sleep-subtitles SECONDS Number of seconds to sleep before each subtitle download ``` ## 视频格式选项: ``` -f, --format FORMAT Video format code, see "FORMAT SELECTION" for more details -S, --format-sort SORTORDER Sort the formats by the fields given, see "Sorting Formats" for more details --format-sort-reset Disregard previous user specified sort order and reset to the default --format-sort-force Force user specified sort order to have precedence over all fields, see "Sorting Formats" for more details (Alias: --S-force) --no-format-sort-force Some fields have precedence over the user specified sort order (default) --video-multistreams Allow multiple video streams to be merged into a single file --no-video-multistreams Only one video stream is downloaded for each output file (default) --audio-multistreams Allow multiple audio streams to be merged into a single file --no-audio-multistreams Only one audio stream is downloaded for each output file (default) --prefer-free-formats Prefer video formats with free containers over non-free ones of the same quality. Use with "-S ext" to strictly prefer free containers irrespective of quality --no-prefer-free-formats Don't give any special preference to free containers (default) --check-formats Make sure formats are selected only from those that are actually downloadable --check-all-formats Check all formats for whether they are actually downloadable --no-check-formats Do not check that the formats are actually downloadable -F, --list-formats List available formats of each video. Simulate unless --no-simulate is used --merge-output-format FORMAT Containers that may be used when merging formats, separated by "/", e.g. "mp4/mkv". Ignored if no merge is required. (currently supported: avi, flv, mkv, mov, mp4, webm) ``` ## 字幕选项: ``` --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 separated by "/", 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" (where "en.*" is a regex pattern that matches "en" followed by 0 or more of any character). 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 ``` ## 认证选项: ``` -u, --username USERNAME Login with this account ID -p, --password PASSWORD Account password. If this option is left out, yt-dlp will ask interactively -2, --twofactor TWOFACTOR Two-factor authentication code -n, --netrc Use .netrc authentication data --netrc-location PATH Location of .netrc authentication data; either the path or its containing directory. Defaults to ~/.netrc --netrc-cmd NETRC_CMD Command to execute to get the credentials for an extractor. --video-password PASSWORD Video-specific password --ap-mso MSO Adobe Pass multiple-system operator (TV provider) identifier, use --ap-list-mso for a list of available MSOs --ap-username USERNAME Multiple-system operator account login --ap-password PASSWORD Multiple-system operator account password. If this option is left out, yt-dlp will ask interactively --ap-list-mso List all supported multiple-system operators --client-certificate CERTFILE Path to client certificate file in PEM format. May include the private key --client-certificate-key KEYFILE Path to private key file for client certificate --client-certificate-password PASSWORD Password for client certificate private key, if encrypted. If not provided, and the key is encrypted, yt-dlp will ask interactively ``` ## 后处理选项: ``` -x, --extract-audio Convert video files to audio-only files (requires ffmpeg and ffprobe) --audio-format FORMAT Format to convert the audio to when -x is used. (currently supported: best (default), aac, alac, flac, m4a, mp3, opus, vorbis, wav). You can specify multiple rules using similar syntax as --remux-video --audio-quality QUALITY Specify ffmpeg audio quality to use when converting the audio with -x. Insert a value between 0 (best) and 10 (worst) for VBR or a specific bitrate like 128K (default 5) --remux-video FORMAT Remux the video into another container if necessary (currently supported: avi, flv, gif, mkv, mov, mp4, webm, aac, aiff, alac, flac, m4a, mka, mp3, ogg, opus, vorbis, wav). If the target container does not support the video/audio codec, remuxing will fail. You can specify multiple rules; e.g. "aac>m4a/mov>mp4/mkv" will remux aac to m4a, mov to mp4 and anything else to mkv --recode-video FORMAT Re-encode the video into another format if necessary. The syntax and supported formats are the same as --remux-video --postprocessor-args NAME:ARGS Give these arguments to the postprocessors. Specify the postprocessor/executable name and the arguments separated by a colon ":" to give the argument to the specified postprocessor/executable. Supported PP are: Merger, ModifyChapters, SplitChapters, ExtractAudio, VideoRemuxer, VideoConvertor, Metadata, EmbedSubtitle, EmbedThumbnail, SubtitlesConvertor, ThumbnailsConvertor, FixupStretched, FixupM4a, FixupM3u8, FixupTimestamp and FixupDuration. The supported executables are: AtomicParsley, FFmpeg and FFprobe. You can also specify "PP+EXE:ARGS" to give the arguments to the specified executable only when being used by the specified postprocessor. Additionally, for ffmpeg/ffprobe, "_i"/"_o" can be appended to the prefix optionally followed by a number to pass the argument before the specified input/output file, e.g. --ppa "Merger+ffmpeg_i1:-v quiet". You can use this option multiple times to give different arguments to different postprocessors. (Alias: --ppa) -k, --keep-video Keep the intermediate video file on disk after post-processing --no-keep-video Delete the intermediate video file after post-processing (default) --post-overwrites Overwrite post-processed files (default) --no-post-overwrites Do not overwrite post-processed files --embed-subs Embed subtitles in the video (only for mp4, webm and mkv videos) --no-embed-subs Do not embed subtitles (default) --embed-thumbnail Embed thumbnail in the video as cover art --no-embed-thumbnail Do not embed thumbnail (default) --embed-metadata Embed metadata to the video file. Also embeds chapters/infojson if present unless --no-embed-chapters/--no-embed-info-json are used (Alias: --add-metadata) --no-embed-metadata Do not add metadata to file (default) (Alias: --no-add-metadata) --embed-chapters Add chapter markers to the video file (Alias: --add-chapters) --no-embed-chapters Do not add chapter markers (default) (Alias: --no-add-chapters) --embed-info-json Embed the infojson as an attachment to mkv/mka video files --no-embed-info-json Do not embed the infojson as an attachment to the video file --parse-metadata [WHEN:]FROM:TO Parse additional metadata like title/artist from other fields; see "MODIFYING METADATA" for details. Supported values of "WHEN" are the same as that of --use-postprocessor (default: pre_process) --replace-in-metadata [WHEN:]FIELDS REGEX REPLACE Replace text in a metadata field using the given regex. This option can be used multiple times. Supported values of "WHEN" are the same as that of --use-postprocessor (default: pre_process) --xattrs Write metadata to the video file's xattrs (using Dublin Core and XDG standards) --concat-playlist POLICY Concatenate videos in a playlist. One of "never", "always", or "multi_video" (default; only when the videos form a single show). All the video files must have the same codecs and number of streams to be concatenable. The "pl_video:" prefix can be used with "--paths" and "--output" to set the output filename for the concatenated files. See "OUTPUT TEMPLATE" for details --fixup POLICY Automatically correct known faults of the file. One of never (do nothing), warn (only emit a warning), detect_or_warn (the default; fix the file if we can, warn otherwise), force (try fixing even if the file already exists) --ffmpeg-location PATH Location of the ffmpeg binary; either the path to the binary or its containing directory --exec [WHEN:]CMD Execute a command, optionally prefixed with when to execute it, separated by a ":". Supported values of "WHEN" are the same as that of --use-postprocessor (default: after_move). The same syntax as the output template can be used to pass any field as arguments to the command. If no fields are passed, %(filepath,_filename|)q is appended to the end of the command. This option can be used multiple times --no-exec Remove any previously defined --exec --convert-subs FORMAT Convert the subtitles to another format (currently supported: ass, lrc, srt, vtt). Use "--convert-subs none" to disable conversion (default) (Alias: --convert- subtitles) --convert-thumbnails FORMAT Convert the thumbnails to another format (currently supported: jpg, png, webp). You can specify multiple rules using similar syntax as "--remux-video". Use "--convert- thumbnails none" to disable conversion (default) --split-chapters Split video into multiple files based on internal chapters. The "chapter:" prefix can be used with "--paths" and "--output" to set the output filename for the split files. See "OUTPUT TEMPLATE" for details --no-split-chapters Do not split video based on chapters (default) --remove-chapters REGEX Remove chapters whose title matches the given regular expression. The syntax is the same as --download-sections. This option can be used multiple times --no-remove-chapters Do not remove any chapters from the file (default) --force-keyframes-at-cuts Force keyframes at cuts when downloading/splitting/removing sections. This is slow due to needing a re-encode, but the resulting video may have fewer artifacts around the cuts --no-force-keyframes-at-cuts Do not force keyframes around the chapters when cutting/splitting (default) --use-postprocessor NAME[:ARGS] The (case-sensitive) name of plugin postprocessors to be enabled, and (optionally) arguments to be passed to it, separated by a colon ":". ARGS are a semicolon ";" delimited list of NAME=VALUE. The "when" argument determines when the postprocessor is invoked. It can be one of "pre_process" (after video extraction), "after_filter" (after video passes filter), "video" (after --format; before --print/--output), "before_dl" (before each video download), "post_process" (after each video download; default), "after_move" (after moving the video file to its final location), "after_video" (after downloading and processing all formats of a video), or "playlist" (at end of playlist). This option can be used multiple times to add different postprocessors ``` ## 赞助商屏蔽选项: 制作章节条目以屏蔽赞助商 从 YouTube 视频中屏蔽使用 [赞助商屏蔽 API](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) 的章节条目,或删除介绍等内容。 ``` --sponsorblock-mark CATS SponsorBlock categories to create chapters for, separated by commas. Available categories are sponsor, intro, outro, selfpromo, preview, filler, interaction, music_offtopic, hook, poi_highlight, chapter, all and default (=all). You can prefix the category with a "-" to exclude it. See [1] for descriptions of the categories. E.g. --sponsorblock-mark all,-preview [1] https://wiki.sponsor.ajay.app/w/Segment_Categories --sponsorblock-remove CATS SponsorBlock categories to be removed from the video file, separated by commas. If a category is present in both mark and remove, remove takes precedence. The syntax and available categories are the same as for --sponsorblock-mark except that "default" refers to "all,-filler" and poi_highlight, chapter are not available --sponsorblock-chapter-title TEMPLATE An output template for the title of the SponsorBlock chapters created by --sponsorblock-mark. The only available fields are start_time, end_time, category, categories, name, category_names. Defaults to "[SponsorBlock]: %(category_names)l" --no-sponsorblock Disable both --sponsorblock-mark and --sponsorblock-remove --sponsorblock-api URL SponsorBlock API location, defaults to https://sponsor.ajay.app ``` ## 提取器选项: ``` --extractor-retries RETRIES Number of retries for known extractor errors (default is 3), or "infinite" --allow-dynamic-mpd Process dynamic DASH manifests (default) (Alias: --no-ignore-dynamic-mpd) --ignore-dynamic-mpd Do not process dynamic DASH manifests (Alias: --no-allow-dynamic-mpd) --hls-split-discontinuity Split HLS playlists to different formats at discontinuities such as ad breaks --no-hls-split-discontinuity Do not split HLS playlists into different formats at discontinuities such as ad breaks (default) --extractor-args IE_KEY:ARGS Pass ARGS arguments to the IE_KEY extractor. See "EXTRACTOR ARGUMENTS" for details. You can use this option multiple times to give arguments for different extractors ``` ## 预设别名: 为方便使用和易于理解,预先定义了别名。请注意,yt-dlp 的未来版本可能会添加或调整预设,但现有预设名称不会更改或删除。 ``` -t mp3 -f 'ba[acodec^=mp3]/ba/b' -x --audio-format mp3 -t aac -f 'ba[acodec^=aac]/ba[acodec^=mp4a.40.]/ba/b' -x --audio-format aac -t mp4 --merge-output-format mp4 --remux-video mp4 -S vcodec:h264,lang,quality,res,fps,hdr:12,a codec:aac -t mkv --merge-output-format mkv --remux-video mkv -t sleep --sleep-subtitles 5 --sleep-requests 0.75 --sleep-interval 10 --max-sleep-interval 20 ``` # 配置 你可以通过将任何受支持的命令行选项放入配置文件来配置 yt-dlp。加载配置的顺序如下: 1. **主配置**: - 通过 `--config-locations` 指定的文件 2. **便携配置**:(推荐用于便携安装) - 二进制文件所在目录的 `yt-dlp.conf` - 如果从源代码运行,则为 `yt-dlp.conf` 在 `yt_dlp` 目录的父目录中 3. **主目录配置**: - `yt-dlp.conf` 在 `-P` 指定的主目录中 - 如果未指定 `-P`,则搜索当前目录 4. **用户配置**: - `${XDG_CONFIG_HOME}/yt-dlp.conf` - `${XDG_CONFIG_HOME}/yt-dlp/config`(Linux/macOS 推荐) - `${XDG_CONFIG_HOME}/yt-dlp/config.txt` - `${APPDATA}/yt-dlp.conf` - `${APPDATA}/yt-dlp/config`(推荐在 Windows 上) - `${APPDATA}/yt-dlp/config.txt` - `~/yt-dlp.conf` - `~/yt-dlp.conf.txt` - `~/.yt-dlp/config` - `~/.yt-dlp/config.txt` 例如,使用以下配置文件,yt-dlp 将始终提取音频、复制修改时间、使用代理,并将所有视频保存在主目录下的 `YouTube` 文件夹中: ``` # Lines starting with # are comments # Always extract audio -x # Copy the mtime --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 中一样。 可以使用 `--ignore-config` 忽略所有配置文件。如果 `--ignore-config` 在某个配置文件中找到,则不会加载后续配置。例如,将该选项放在便携配置文件中可阻止加载主目录、用户和系统配置。 此外(出于向后兼容性),如果 `--ignore-config` 在系统配置文件中找到,则不会加载用户配置。 ### 配置文件编码 根据系统区域设置解码配置文件,如果存在 UTF BOM 则使用 UTF-8,否则使用系统区域设置。 如果希望以不同编码方式解码文件,请在文件开头添加 `# coding: ENCODING`(例如 `# coding: shift-jis`)。开头不能有任何字符,包括空格或 BOM。 ### 使用 netrc 进行认证 你可能希望为支持认证的提取器配置自动存储凭据(通过提供用户名和密码),以避免每次运行 yt-dlp 时都将凭据作为命令行参数传递,并防止在 Shell 命令历史中记录明文密码。你可以使用 [`.netrc` 文件](https://link.zhihu.com/?target=https%3A%2F%2Fen.wikipedia.org/wiki/.netrc) 来实现此目的。 为此,需要在 `--netrc-location` 指定的位置创建一个 `.netrc` 文件并限制权限仅供读写: ``` touch ${HOME}/.netrc chmod a-rwx,u+rw ${HOME}/.netrc ``` 之后,可以按以下格式为提取器添加凭据,其中 *extractor* 是提取器名称的小写形式: ``` machine login password ``` 例如: ``` machine youtube login myaccount@gmail.com password my_youtube_password machine twitch login my_twitch_account_name password my_twitch_password ``` 要激活使用 `.netrc` 文件的认证,应传递 `--netrc` 给 yt-dlp 或将其放在 [配置文件中](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Configuration#configuration-file)。 作为使用 `.netrc` 文件的替代方案,可以配置自定义 shell 命令来提供提取器的凭据。这通过提供 `--netrc-cmd` 参数实现,该参数应输出凭据的 netrc 格式并返回 0 表示成功,其他值将被视为错误。 例如,要使用加密的 `.netrc` 文件(存储为 `.authinfo.gpg`): ``` yt-dlp --netrc-cmd 'gpg --decrypt ~/.authinfo.gpg' 'https://www.youtube.com/watch?v=BaW_jenozKc' ``` ### 关于环境变量的说明 * 环境变量通常指定为 `${VARIABLE}`/`$VARIABLE`(UNIX)和 `%VARIABLE%`(Windows);但文档中始终显示为 `${VARIABLE}` * yt-dlp 也允许在 Windows 上使用 UNIX 风格的环境变量用于路径类选项;例如 `--output`、`--config-locations` * 如果未设置,`${XDG_CONFIG_HOME}` 默认为 `~/.config`,`${XDG_CACHE_HOME}` 默认为 `~/.cache` * 在 Windows 上,`~` 指向 `${HOME}`(如果存在);否则指向 `${USERPROFILE}` 或 `${HOMEDRIVE}${HOMEPATH}` * 在 Windows 上,`${USERPROFILE}` 通常指向 `C:\Users\<用户名>`,`${APPDATA}` 指向 `${USERPROFILE}\AppData\Roaming` # 输出模板 `-o` 选项用于指定输出文件名模板,`-P` 选项用于指定各类文件的保存路径。 **简述**:[导航到示例](#output-template-examples)。 最简单的用法是不设置任何模板参数直接下载单个文件,例如 `yt-dlp -o funny_video.flv "https://some/video"`(不推荐硬编码文件扩展名,这样可能会破坏后处理)。 但模板也可以包含在下载每个视频时会被替换的特殊序列。特殊序列可以按照 [Python 字符串格式化操作](https://docs.python.org/3/library/string.html) 进行格式化,例如 `%(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. **算术运算**可以对数字字段进行简单的算术运算;例如 `%(playlist_index+10)03d`、`%(n_entries+1-playlist_index)d` 3. **日期/时间格式化**:日期时间字段可以按照 [strftime 格式化](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format) 进行格式化;例如 `%(duration>%H-%M-%S)s`、`%(upload_date>%Y-%m-%d)s`、`%(epoch-3600>%H-%M-%S)s` 4. **备选字段**:可以使用逗号分隔备选字段;例如 `%(release_date>%Y,upload_date>%Y|Unknown)s` 5. **替换**:可以使用 `&` 分隔符按照 [`str.format` 小语言](https://docs.python.org/3/library/string.html#format-string-syntax) 进行替换。如果字段非空,则使用此替换值而非实际字段内容。这在备选字段之后考虑;因此替换值会在任意备选字段非空时使用。例如 `%(chapters&has chapters|no chapters)s`、`%(title&TITLE={:>20}|NO TITLE)s` 6. **默认值**:可以使用 `|` 分隔符指定字段的默认值,覆盖 `--output-na-placeholder`;例如 `%(uploader|Unknown)s` 7. **更多转换**:除了常规格式类型 `diouxXeEfFgGcrs`,yt-dlp 还支持转换为 `B` = **B**ytes、`j` = **j**son(`#` 用于美化打印,`+` 用于 Unicode)、`h` = HTML 转义、`l` = 逗号分隔的**列表**(`#` 用于换行符分隔)、`q` = 字符串**引用**(`#` 用于拆分列表为不同参数)、`D` = 添加 **D**ecimal 后缀(`#` 用于使用 1024 作为因子),以及 `S` = **S**anitize 作为文件名(`**` 用于受限字符)。 8. **Unicode 规范化**:格式类型 `U` 可用于 NFC [Unicode 规范化](https://unicode.org/reports/tr15/)。备选形式标志(`#`)可更改为 NFD,转换标志(`+`)可用于 NFKC/NFKD 兼容性等价规范化。例如 `%(title)+.100U` 是 NFKC。 总结来说,字段的一般语法为: ``` %(name[.keys][addition][>strf][,alternate][&replacement][|default])[flags][width][.precision][length]type ``` 此外,可以为各种元数据文件单独设置输出模板(而非通用模板),文件类型包括 `subtitle`、`thumbnail`、`description`、`annotation`(已弃用)、`infojson`、`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:"` 仅对播放列表写入缩略图,而不写入视频。 **注意**:由于后处理(例如合并等),实际输出文件名可能不同。使用 `--print after_move:filepath` 查看后处理完成后的文件名。 可用字段包括: - `id`(字符串):视频标识符 - `title`(字符串):视频标题 - `fulltitle`(字符串):视频标题(忽略直播时间戳和通用标题) - `ext`(字符串):视频文件扩展名 - `alt_title`(字符串):视频副标题 - `description`(字符串):视频描述 - `display_id`(字符串):视频的替代标识符 - `uploader`(字符串):视频上传者全名 - `uploader_id`(字符串):视频上传者昵称或 ID - `uploader_url`(字符串):上传者个人资料 URL - `license`(字符串):视频授权许可 - `creators`(列表):视频创作者 - `creator`(字符串):视频创作者(逗号分隔) - `timestamp`(数字):视频可用时间的时间戳 - `upload_date`(字符串):视频上传日期(UTC,格式 YYYYMMDD) - `release_timestamp`(数字):视频发布时间的时间戳 - `release_date`(字符串):视频发布日期(UTC,格式 YYYYMMDD) - `release_year`(数字):视频或专辑发布年份 - `modified_timestamp`(数字):视频最后修改时间的时间戳 - `modified_date`(字符串):视频最后修改日期(UTC,格式 YYYYMMDD) - `channel`(字符串):上传视频的频道全名 - `channel_id`(字符串):频道 ID - `channel_url`(字符串):频道 URL - `channel_follower_count`(数字):频道关注者数量 - `channel_is_verified`(布尔值):频道是否已验证 - `location`(字符串):视频拍摄地点 - `duration`(数字):视频时长(秒) - `duration_string`(字符串):视频时长(HH:mm:ss) - `view_count`(数字):观看次数 - `concurrent_view_count`(数字):当前观看次数 - `like_count`(数字):点赞数 - `dislike_count`(数字):点踩数 - `repost_count`(数字):转发数 - `average_rating`(数字):平均评分 - `comment_count`(数字):评论数 - `save_count`(数字):保存或收藏次数 - `age_limit`(数字):年龄限制(年) - `live_status`(字符串):直播状态(not_live、is_live、is_upcoming、was_live、post_live) - `is_live`(布尔值):是否为直播 - `was_live`(布尔值):是否曾是直播 - `playable_in_embed`(字符串):是否允许嵌入播放 - `availability`(字符串):可用性(private、premium_only、subscriber_only、needs_auth、unlisted、public) - `media_type`(字符串):媒体类型(如 episode、clip、trailer) - `start_time`(数字):开始时间(秒) - `end_time`(数字):结束时间(秒) - `extractor`(字符串):提取器名称 - `extractor_key`(字符串):提取器键 - `epoch`(数字):信息提取完成的 Unix 时间戳 - `autonumber`(数字):自动编号,从 `--autonumber-start` 开始 - `video_autonumber`(数字):视频自动编号 - `n_entries`(数字):提取的项目总数 - `playlist_id`(字符串):播放列表 ID - `playlist_title`(字符串):播放列表标题 - `playlist`(字符串):播放列表标题或 ID - `playlist_count`(数字):播放列表中的项目总数 - `playlist_index`(数字):视频在播放列表中的索引(补零) - `playlist_autonumber`(数字):视频在播放队列中的位置(补零) - `playlist_uploader`(字符串):播放列表上传者 - `playlist_uploader_id`(字符串):播放列表上传者 ID - `playlist_channel`(字符串):播放列表频道显示名 - `playlist_channel_id`(字符串):播放列表频道 ID - `playlist_webpage_url`(字符串):播放列表网页 URL - `webpage_url`(字符串):视频网页 URL - `webpage_url_basename`(字符串):网页 URL 的基础名 - `webpage_url_domain`(字符串):网页 URL 的域名 - `original_url`(字符串):用户提供的原始 URL - `categories`(列表):视频所属类别 - `tags`(列表):视频标签 - `cast`(列表):演员列表 所有上述字段在 [格式化过滤器](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Formatting-filters) 中也可使用。 对于属于某个逻辑章节或部分的视频: - `chapter`(字符串):章节名称或标题 - `chapter_number`(数字):章节编号 - `chapter_id`(字符串):章节 ID 对于作为系列或节目一部分的剧集: - `series`(字符串):系列或节目标题 - `series_id`(字符串):系列或节目 ID - `season`(字符串):季标题 - `season_number`(数字):季编号 - `season_id`(字符串): ID - `episode`(字符串):剧集标题 - `episode_number`(数字):季内剧集编号 - `episode_id`(字符串):剧集 ID 对于作为音乐专辑一部分的音轨: - `track`(字符串):音轨标题 - `track_number`(数字):音轨编号 - `track_id`(字符串):音轨 ID - `artists`(列表):艺术家列表 - `artist`(字符串):艺术家(逗号分隔) - `genres`(列表):流派列表 - `genre`(字符串):流派(逗号分隔) - `composers`(列表):作曲家列表 - `composer`(字符串):作曲家(逗号分隔) - `album`(字符串):专辑标题 - `album_type`(字符串):专辑类型 - `album_artists`(列表):专辑所有艺术家 - `album_artist`(字符串):专辑所有艺术家(逗号分隔) - `disc_number`(数字):光盘编号 仅在使用 `--download-sections` 并针对具有内部章节的视频启用 `--split-chapters` 时可用: - `section_title`(字符串):章节标题 - `section_number`(数字):章节编号 - `section_start`(数字):章节开始时间(秒) - `section_end`(数字):章节结束时间(秒) 仅在使用 `--print` 时可用: - `urls`(字符串):所有请求格式的 URL,每行一个 - `filename`(字符串):视频文件名。请注意,实际文件名可能不同。 - `formats_table`(表格):视频格式表(通过 `--list-formats` 打印) - `thumbnails_table`(表格):缩略图格式表(通过 `--list-thumbnails` 打印) - `subtitles_table`(表格):字幕格式表(通过 `--list-subs` 打印) - `automatic_captions_table`(表格):自动字幕格式表(通过 `--list-subs` 打印) 下载后(`post_process`/`after_move`): - `filepath`(字符串):实际下载视频文件的路径 仅在使用 `--sponsorblock-chapter-title` 时可用: - `start_time`(数字):章节开始时间(秒) - `end_time`(数字):章节结束时间(秒) - `categories`(列表):章节所属的 [SponsorBlock 类别](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) - `category`(字符串):最小的 SponsorBlock 类别 - `category_names`(列表):类别的友好名称 - `name`(字符串):最小类别的友好名称 - `type`(字符串):章节的 [SponsorBlock 动作类型](https://link.zhihu.com/?target=https%3A%2F%2Fsponsor.ink%2F) 每个上述序列在输出模板中引用时将被替换为对应的实际值。例如,对于 `-o %(title)s-%(id)s.%(ext)s` 和一个 mp4 视频,标题为 `yt-dlp test video`,ID 为 `BaW_jenozKc`,这将创建一个 `yt-dlp test video-BaW_jenozKc.mp4` 文件,创建在当前目录。 **注意**:某些序列可能不存在,因为它们依赖于特定提取器获取的元数据。此类序列将被占位符值替换(由 `--output-na-placeholder` 提供,默认为 `NA`)。 **提示**:使用 `-j` 查看特定 URL 的可用字段。 对于数字序列,可以使用 [数字相关格式化](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Formatting-filters);例如 `%(view_count)05d` 将生成一个字符串,其中观看次数用零填充到 5 位,例如 `00042`。 输出模板也可以包含任意层次路径;例如 `-o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s"` 将导致每个视频下载在对应路径模板创建的目录中。任何缺失的目录都会自动为你创建。 要使用输出模板中的百分文字面量,请使用 `%%`。要输出到 stdout,请使用 `-o -`。 当前默认模板为 `%(title)s [%(id)s].%(ext)s`。 在某些情况下,你不希望特殊字符(如中文、空格或 &)出现在文件名中,例如在将下载的文件传输到 Windows 系统或通过 8 位不安全通道传输文件名时。在这种情况下,添加 `--restrict-filenames` 标志以获得更短的文件名。 #### 输出模板示例 ``` $ yt-dlp --print filename -o "test video.%(ext)s" BaW_jenozKc test video.webm # Literal name with correct extension $ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc youtube-dl test video ''_ä↭𝕐.webm # All kinds of weird characters $ yt-dlp --print filename -o "%(title)s.%(ext)s" BaW_jenozKc --restrict-filenames youtube-dl_test_video_.webm # Restricted file name # Download YouTube playlist videos in separate directory indexed by video order in a playlist $ yt-dlp -o "%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re" # Download YouTube playlist videos in separate directories according to their uploaded year $ yt-dlp -o "%(upload_date>%Y)s/%(title)s.%(ext)s" "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re" # Prefix playlist index with " - " separator, but only if it is available $ yt-dlp -o "%(playlist_index&{} - |)s%(title)s.%(ext)s" BaW_jenozKc "https://www.youtube.com/user/TheLinuxFoundation/playlists" # Download all playlists of YouTube channel/user keeping each playlist in separate directory: $ yt-dlp -o "%(uploader)s/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s" "https://www.youtube.com/user/TheLinuxFoundation/playlists" # Download Udemy course keeping each chapter in separate directory under MyVideos directory in your home $ yt-dlp -u user -p password -P "~/MyVideos" -o "%(playlist)s/%(chapter_number)s - %(chapter)s/%(title)s.%(ext)s" "https://www.udemy.com/java-tutorial" # Download entire series season keeping each series and each season in separate directory under C:/MyVideos $ yt-dlp -P "C:/MyVideos" -o "%(series)s/%(season_number)s - %(season)s/%(episode_number)s - %(episode)s.%(ext)s" "https://videomore.ru/kino_v_detalayah/5_sezon/367617" # Download video as "C:\MyVideos\uploader\title.ext", subtitles as "C:\MyVideos\subs\uploader\title.ext" # and put all temporary files in "C:\MyVideos\tmp" $ yt-dlp -P "C:/MyVideos" -P "temp:tmp" -P "subtitle:subs" -o "%(uploader)s/%(title)s.%(ext)s" BaW_jenozKc --write-subs # Download video as "C:\MyVideos\uploader\title.ext" and subtitles as "C:\MyVideos\uploader\subs\title.ext" $ yt-dlp -P "C:/MyVideos" -o "%(uploader)s/%(title)s.%(ext)s" -o "subtitle:%(uploader)s/subs/%(title)s.%(ext)s" BaW_jenozKc --write-subs # Stream the video being downloaded to stdout $ yt-dlp -o - BaW_jenozKc ``` # 格式选择 默认情况下,yt-dlp 尝试下载最佳可用质量,如果你**不**传递任何选项。 这通常等同于使用 `-f bestvideo*+bestaudio/best`。然而,如果启用了多音频流(`--audio-multistreams`),默认格式会变为 `-f bestvideo+bestaudio/best`。同样,如果 ffmpeg 不可用,或你使用 yt-dlp 流式传输到 `stdout`(`-o -`),默认变为 `-f best/bestvideo+bestaudio`。 **弃用警告**:最新版本的 yt-dlp 可以同时将多个格式流式传输到标准输出,使用 ffmpeg。所以,在未来版本中,默认值将设置为 `-f bv*+ba/b`,类似于普通下载。如果希望保留 `-f b/bv+ba` 设置,建议在配置选项中明确指定。 格式选择的一般语法是 `-f FORMAT`(或 `--format FORMAT`),其中 `FORMAT` 是一个 *选择器表达式*,即描述你希望下载的格式或格式的表达式。 **简述**:[导航到示例](#format-selection-examples)。 最简单的场景是请求特定格式;例如使用 `-f 22` 可以下载格式代码等于 22 的格式。你可以使用 `--list-formats` 或 `-F` 获取特定视频的可用格式代码列表。请注意,这些格式代码是提取器特定的。 你也可以使用文件扩展名(当前支持 `3gp`、`aac`、`flv`、`m4a`、`mp3`、`mp4`、`ogg`、`wav`、`webm`)来下载特定扩展名的最佳质量格式作为单个文件,例如 `-f webm` 将下载最佳质量格式且扩展名为 `webm` 的单个文件。 你可以使用 `-f -` 交互式地为每个视频提供格式选择器 你还可以使用特殊名称来选择特定边缘情况格式: - `all`:选择**所有格式**单独 - `mergeall`:选择并**合并所有格式**(必须与 `--audio-multistreams`、`--video-multistreams` 或两者一起使用) - `b*`、`best*`:选择最佳质量格式,**包含**视频或音频或两者(即 `vcodec!=none or acodec!=none`) - `b`、`best`:选择最佳质量格式,**同时包含**视频和音频。相当于 `best*[vcodec!=none][acodec!=none]` - `bv`、`bestvideo`:选择最佳质量**仅视频**格式。相当于 `best*[acodec=none]` - `bv*`、`bestvideo*`:选择最佳质量**包含视频**的格式。它可能也包含音频。相当于 `best*[vcodec!=none]` - `ba`、`bestaudio`:选择最佳质量**仅音频**格式。相当于 `best*[vcodec=none]` - `ba*`、`bestaudio*`:选择最佳质量**包含音频**的格式。它可能也包含视频。相当于 `best*[acodec!=none]`(**不推荐使用**) - `w*`、`worst*`:选择最差质量格式,**包含**视频或音频 - `w`、`worst`:选择最差质量格式,**同时包含**视频和音频。相当于 `worst*[vcodec!=none][acodec!=none]` - `wv`、`worstvideo`:选择最差质量**仅视频**格式。相当于 `worst*[acodec=none]` - `wv*`、`worstvideo*`:选择最差质量**包含视频**的格式。它可能也包含音频。相当于 `worst*[vcodec!=none]` - `wa`、`worstaudio`:选择最差质量**仅音频格式。相当于 `worst*[vcodec=none]` - `wa*`、`worstaudio*`:选择最差质量**包含音频**的格式。它可能也包含视频。相当于 `worst*[acodec!=none]` 例如,要下载最差的视频仅格式,可以使用 `-f worstvideo`。不过,不推荐使用 `worst` 和相关选项。当格式选择器为 `worst` 时,会选择所有方面最差的格式。通常你实际想要的是文件大小最小的视频。因此,通常更推荐使用 `-S +size` 或更严谨地 `-S +size,+br,+res,+fps` 替代 `-f worst`。详见 [格式排序](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Formatting-sort) 对于更多细节。 你可以通过使用 `best.` 选择某类型下的第 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 ++...` 合并视频和音频的格式(需要安装 ffmpeg);例如 `-f bestvideo+bestaudio` 将下载最佳视频仅格式、最佳音频仅格式,并使用 ffmpeg 合并它们。 **弃用警告**:由于以下描述的行为复杂且反直觉,此行为将被移除,多流支持将默认启用。新的操作符将添加以限制格式为单音频/视频流 除非使用 `--video-multistreams`,否则所有包含视频流的格式(除了第一个)将被忽略。类似地,除非使用 `--audio-multistreams`,否则所有包含音频流的格式(除了第一个)将被忽略。例如,`-f bestvideo+best+bestaudio --video-multistreams --audio-multistreams` 将下载并合并所有 3 个给定格式。结果文件将包含 2 个视频流和 2 个音频流。但 `-f bestvideo+best+bestaudio --no-video-multistreams` 将仅下载并合并 `bestvideo` 和 `bestaudio`。`best` 将被忽略,因为已选择了包含视频流的格式(`bestvideo`)。格式顺序很重要:`-f best+bestaudio --no-audio-multistreams` 将仅下载 `best`,而 `-f bestaudio+best --no-audio-multistreams` 将忽略 `best` 并仅下载 `bestaudio`。 ## 格式过滤 你也可以通过使用括号中的条件来过滤视频格式,例如 `-f "best[height=720]"`(或 `-f "[filesize>10M]"` 因为没有选择器时会被解释为 `best`)。 以下数字元字段可用于比较 `<`、`<=`、`>`、`>=`、`=`(等于)、`!=`(不等于): - `filesize`:字节数,如果提前已知 - `filesize_approx`:字节数的估计值 - `width`:视频宽度,如果已知 - `height`:视频高度,如果已知 - `aspect_ratio`:视频宽高比,如果已知 - `tbr`:平均比特率(kbps) - `abr`:平均音频比特率(kbps) - `vbr`:平均视频比特率(kbps) - `asr`:音频采样率(Hz) - `fps`:帧速率 - `audio_channels`:音频通道数 - `stretched_ratio`:视频像素的宽高比(如果不是正方形) 字符串元字段也可以用于过滤: - `url`:视频 URL - `ext`:文件扩展名 - `acodec`:使用的音频编解码器 - `vcodec`:使用的视频编解码器 - `container`:容器格式名称 - `protocol`:用于实际下载的协议(小写)(`http`、`https`、`rtsp`、`rtmp`、`rtmpe`、`mms`、`f4m`、`ism`、`http_dash_segments`、`m3u8`、`m3u8_native`) - `language`:语言代码 - `dynamic_range`:视频的动态范围 - `format_id`:格式的简短描述 - `format`:人类可读的格式描述 - `format_note`:关于格式的附加信息 - `resolution`:宽度和高度的文本描述 任何字符串比较都可以通过前缀 `!` 进行否定,以产生相反的比较,例如 `!*=`(不包含)。比较的字符串值需要用单引号或双引号括起来,如果包含空格或特殊字符(除了 `._-`)。 **注意**:上述元字段并非保证存在,因为这完全取决于特定提取器提供的元数据,即网站提供的元数据。任何其他由提取器提供的字段也可以用于过滤。 如果某个字段的值未知,则会排除该格式,除非你在操作符后添加 `?`。你可以组合格式过滤器,例如 `-f "bv[height<=?720][tbr>500]"` 会选择高度不超过 720p(或高度未知)且比特率至少为 500 kbps 的视频格式。你也可以使用带有 `all` 的过滤器来下载所有满足条件的格式,例如 `-f "all[vcodec=none]"` 会下载所有仅音频的格式。 格式选择器也可以使用括号进行分组;例如 `-f "(mp4,webm)[height<480]"` 将下载最大高度小于 480 的最佳预合并 mp4 和 webm 格式。 ## 格式排序 你可以使用 `-S`(`--format-sort`)更改被视为“最佳”的标准。格式为 `--format-sort field1,field2...`。 可用字段包括: - `hasvid`:优先选择包含视频流的格式 - `hasaud`:优先选择包含音频流的格式 - `ie_pref`:格式偏好 - `lang`:语言偏好(由提取器确定,例如原始语言优先于音频描述) - `quality`:格式质量 - `source`:来源偏好 - `proto`:下载协议(`https`/`ftps` > `http`/`ftp` > `m3u8_native`/`m3u8` > `http_dash_segments` > `websocket_frag` > `mms`/`rtsp` > `f4f`/`f4m`) - `vcodec`:视频编解码器(`av01` > `vp9.2` > `vp9` > `h265` > `h264` > `vp8` > `h263` > `theora` > 其他) - `acodec`:音频编解码器(`flac`/`alac` > `wav`/`aiff` > `opus` > `vorbis` > `aac` > `mp4a` > `mp3` > `ac4` > `eac3` > `ac3` > `dts` > 其他) - `codec`:等效于 `vcodec,acodec` - `vext`:视频扩展名(`mp4` > `mov` > `webm` > `flv` > 其他)。如果使用 `--prefer-free-formats`,则 `webm` 优先 - `aext`:音频扩展名(`m4a` > `aac` > `mp3` > `ogg` > `opus` > `webm` > 其他)。如果使用 `--prefer-free-formats`,则顺序变为 `ogg` > `opus` > `webm` > `mp3` > `m4a` > `aac` - `ext`:等效于 `vext,aext` - `filesize`:精确文件大小,如果提前已知 - `fs_approx`:近似文件大小 - `size`:精确文件大小(如果可用),否则为近似大小 - `height`:视频高度 - `width`:视频宽度 - `res`:视频分辨率,计算为最小的维度 - `fps`:视频帧速率 - `hdr`:视频的动态范围(`DV` > `HDR12` > `HDR10+` > `HDR10` > `HLG` > `SDR`) - `channels`:音频通道数 - `tbr`:总平均比特率(kbps) - `vbr`:平均视频比特率(kbps) - `abr`:平均音频比特率(kbps) - `br`:平均比特率(kbps),`tbr`/`vbr`/`abr` - `asr`:音频采样率(Hz) **弃用警告**:许多这些字段有(目前未记录的)别名,可能在将来的版本中移除。建议仅使用文档中记录的字段名。 所有字段,默认按降序排序。要反转顺序,请在该字段前加 `+`。例如 `+res` 优先选择分辨率最小的格式。此外,可以为字段指定首选值,用 `:` 分隔。例如 `res:720` 优先选择分辨率不超过 720p 的视频,且在没有小于 720p 的视频时选择最小的视频。如果对 `codec` 和 `ext` 指定两个首选值,第一个用于视频,第二个用于音频。例如 `+codec:avc:m4a`(等价于 `+vcodec:avc,+acodec:m4a`)设置视频编解码器偏好为 `h264` > `h265` > `vp9` > `vp9.2` > `av01` > `vp8` > `h263` > `theora`,音频编解码器偏好为 `mp4a` > `aac` > `vorbis` > `opus` > `mp3` > `ac3` > `dts`。你也可以使用 `~` 作为分隔符来指定接近的值。例如 `filesize~1G` 优先选择文件大小最接近 1 GiB 的格式。 字段 `hasvid` 和 `ie_pref` 始终被赋予最高优先级,无论用户定义的顺序如何。此行为可以通过使用 `--format-sort-force` 更改。除了这些之外,默认顺序为:`lang,quality,res,fps,hdr:12,vcodec,channels,acodec,size,br,asr,proto,ext,hasaud,source,id`。提取器可以覆盖此默认顺序,但不能覆盖用户提供的顺序。 注意:默认的 `hdr` 为 `hdr:12`;即不优先选择 Dolby Vision。此选择是因为 DV 格式尚未完全兼容大多数设备。未来可能会更改。 如果格式选择器为 `worst`,则在排序后选择最后一项。这意味着它会选择所有方面最差的格式。大多数时候,你实际想要的是文件大小最小的视频。因此,通常更推荐使用 `-f best -S +size,+br,+res,+fps`。 如果你多次使用 `-S`/`--format-sort`,每个后续排序参数将前置到前一个参数中,并且仅保留任何重复字段的最高优先级。例如,`-S proto -S res` 等价于 `-S res,proto`,而 `-S res:720,fps -S vcodec,res:1080` 等价于 `-S vcodec,res:1080,fps`。你可以使用 `--format-sort-reset` 忽略任何先前传递的 `-S`/`--format-sort` 参数并重置为默认顺序。 **提示**:你可以使用 `-v -F` 查看格式排序方式(从最差到最佳)。 ## 格式选择示例 ``` # Download and merge the best video-only format and the best audio-only format, # or download the best combined format if video-only format is not available $ yt-dlp -f "bv+ba/b" # Download best format that contains video, # and if it doesn't already have an audio stream, merge it with best audio-only format $ yt-dlp -f "bv*+ba/b" # Same as above $ yt-dlp # Download the best video-only format and the best audio-only format without merging them # For this case, an output template should be used since # by default, bestvideo and bestaudio will have the same file name. $ yt-dlp -f "bv,ba" -o "%(title)s.f%(format_id)s.%(ext)s" # Download and merge the best format that has a video stream, # and all audio-only formats into one file $ yt-dlp -f "bv*+mergeall[vcodec=none]" --audio-multistreams # Download and merge the best format that has a video stream, # and the best 2 audio-only formats into one file $ yt-dlp -f "bv*+ba+ba.2" --audio-multistreams # The following examples show the old method (without -S) of format selection # and how to use -S to achieve a similar but (generally) better result # Download the worst video available (old method) $ yt-dlp -f "wv*+wa/w" # Download the best video available but with the smallest resolution $ yt-dlp -S "+res" # Download the smallest video available $ yt-dlp -S "+size,+br" # Download the best mp4 video available, or the best video if no mp4 available $ yt-dlp -f "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4] / bv*+ba/b" # Download the best video with the best extension # (For video, mp4 > mov > webm > flv. For audio, m4a > aac > mp3 ...) $ yt-dlp -S "ext" # Download the best video available but no better than 480p, # or the worst video if there is no video under 480p $ yt-dlp -f "bv*[height<=480]+ba/b[height<=480] / wv*+ba/w" # Download the best video available with the largest height but no better than 480p, # or the best video with the smallest resolution if there is no video under 480p $ yt-dlp -S "height:480" # Download the best video available with the largest resolution but no better than 480p, # or the best video with the smallest resolution if there is no video under 480p # Resolution is determined by using the smallest dimension. # So this works correctly for vertical videos as well $ yt-dlp -S "res:480" # Download the best video (that also has audio) but no bigger than 50 MB, # or the worst video (that also has audio) if there is no video under 50 MB $ yt-dlp -f "b[filesize<50M] / w" # Download the largest video (that also has audio) but no bigger than 50 MB, # or the smallest video (that also has audio) if there is no video under 50 MB $ yt-dlp -f "b" -S "filesize:50M" # Download the best video (that also has audio) that is closest in size to 50 MB $ yt-dlp -f "b" -S "filesize~50M" # Download best video available via direct link over HTTP/HTTPS protocol, # or the best video available via any protocol if there is no such video $ yt-dlp -f "(bv*+ba/b)[protocol^=http][protocol!*=dash] / (bv*+ba/b)" # Download best video available via the best protocol # (https/ftps > http/ftp > m3u8_native > m3u8 > http_dash_segments ...) $ yt-dlp -S "proto" # Download the best video with either h264 or h265 codec, # or the best video if there is no such video $ yt-dlp -f "(bv*[vcodec~='^((he|a)vc|h26[45])']+ba) / (bv*+ba/b)" # Download the best video with best codec no better than h264, # or the best video with worst codec if there is no such video $ yt-dlp -S "codec:h264" # Download the best video with worst codec no worse than h264, # or the best video with best codec if there is no such video $ yt-dlp -S "+codec:h264" # More complex examples # Download the best video no better than 720p preferring framerate greater than 30, # or the worst video (still preferring framerate greater than 30) if there is no such video $ yt-dlp -f "((bv*[fps>30]/bv*)[height<=720]/(wv*[fps>30]/wv*)) + ba / (b[fps>30]/b)[height<=720]/(w[fps>30]/w)" # Download the video with the largest resolution no better than 720p, # or the video with the smallest resolution available if there is no such video, # preferring larger framerate for formats with the same resolution $ yt-dlp -S "res:720,fps" # Download the video with smallest resolution no worse than 480p, # or the video with the largest resolution available if there is no such video, # preferring better codec and then larger total bitrate for the same resolution $ yt-dlp -S "+res:480,codec,br" ``` # 修改元数据 通过 `--parse-metadata` 和 `--replace-in-metadata` 可以修改获取的元数据。 `--replace-in-metadata FIELDS REGEX REPLACE` 用于使用 [Python 正则表达式](https://docs.python.org/3/library/re.html) 替换任何元数据字段中的文本。[反向引用](https://docs.python.org/3/library/re.html#re.sub) 可用于高级用途。 `--parse-metadata FROM:TO` 的通用语法是给出要从中提取数据的字段或 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax),以及要解释为的格式,用冒号 `:` 分隔。可以使用 [Python 正则表达式](https://docs.python.org/3/library/re.html)(带命名捕获组)、单个字段名,或类似 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax) 的语法(仅支持 `%(field)s` 格式)用于 `TO`。该选项可以多次使用以解析和修改各种字段。 注意这些选项保留其相对顺序,允许在解析字段后进行替换,反之亦然。此外,由此创建的任何字段都可用于 [输出模板](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/wiki/Output-template-syntax) 并影响使用 `--embed-metadata` 添加到媒体文件的元数据。 此选项还有几个特殊用途: * 你可以下载一个额外的 URL,基于当前下载视频的元数据。要实现这一点,将字段 `additional_urls` 设置为要下载的 URL。例如 `--parse-metadata "description:(?Phttps?://www\.vimeo\.com/\d+)"` 将下载描述中第一个找到的 vimeo 视频 * 你可以使用此选项修改嵌入媒体文件中的元数据。为此,将对应字段的值设置为带有 `meta_` 前缀的值。例如,任何设置到 `meta_description` 字段的值将添加到文件的 `description` 字段中——你可以使用此功能设置不同的“描述”和“概要”。要修改各个流的元数据,请使用 `meta_` 前缀(例如 `meta1_language`)。任何设置到 `meta_` 字段的值将覆盖所有默认值。 **注意**:元数据修改发生在格式选择、提取后和其他后处理操作之前。某些字段可能会在此步骤中添加或更改,从而覆盖你的更改。 默认情况下,yt-dlp 会向文件添加以下元数据: 元数据字段 | 来源 :----------|:------------------------------------------------ `title` | `track` 或 `title` `date` | `upload_date` `description`, `synopsis` | `description` `purl`, `comment` | `webpage_url` `track` | `track_number` `artist` | `artist`, `artists`, `creator`, `creators`, `uploader` 或 `uploader_id` `composer` | `composer` 或 `composers` `genre` | `genre`, `genres`, `categories` 或 `tags` `album` | `album` 或 `series` `album_artist` | `album_artist` 或 `album_artists` `disc` | `disc_number` `show` | `series` `season_number` | `season_number` `episode_id` | `episode` 或 `episode_id` `episode_sort` | `episode_number` `language` of each stream | 该格式的 `language` **注意**:文件格式可能不支持这些字段 ## 修改元数据示例 ``` # Interpret the title as "Artist - Title" $ yt-dlp --parse-metadata "title:%(artist)s - %(title)s" # Regex example $ yt-dlp --parse-metadata "description:Artist - (?P.+)" # Copy the episode field to the title field (with FROM and TO as single fields) $ yt-dlp --parse-metadata "episode:title" # Set title as "Series name S01E05" $ yt-dlp --parse-metadata "%(series)s S%(season_number)02dE%(episode_number)02d:%(title)s" # Prioritize uploader as the "artist" field in video metadata $ yt-dlp --parse-metadata "%(uploader|)s:%(meta_artist)s" --embed-metadata # Set "comment" field in video metadata using description instead of webpage_url, # handling multiple lines correctly $ yt-dlp --parse-metadata "description:(?s)(?P.+)" --embed-metadata # Do not set any "synopsis" in the video metadata $ yt-dlp --parse-metadata ":(?P)" # Remove "formats" field from the infojson by setting it to an empty string $ yt-dlp --parse-metadata "video::(?P)" --write-info-json # Replace all spaces and "_" in title and uploader with a `-` $ yt-dlp --replace-in-metadata "title,uploader" "[ _]" "-" ``` # 提取器参数 某些提取器接受可通过 `--extractor-args KEY:ARGS` 传递的附加参数。`ARGS` 是以 `;`(分号)分隔的 `ARG=VAL1,VAL2` 字符串。例如 `--extractor-args "youtube:player-client=tv,mweb;formats=incomplete" --extractor-args "twitter:api=syndication"` **注意**:在 CLI 中,`ARG` 可以使用 `-` 替代 `_`;例如 `youtube:player-client"` 变为 `youtube:player_client"` 以下提取器使用此功能: #### youtube * `lang`:优先使用此语言代码(区分大小写)翻译的元数据(`title`、`description` 等)。默认优先使用视频主要语言元数据,并回退到 `en` 翻译。参见 [youtube/_base.py](https://github.com/yt-dlp/yt-dlp/blob/master/youtube/_base.py) 获取支持的内容语言代码列表 * `skip`:一个或多个 `hls`、`dash` 或 `translated_sub`,用于跳过提取 m3u8 清单、dash 清单和 [自动翻译字幕](https://link.zhihu.com/?target=https%3A%2F%2Fgithub.com/yt-dlp/yt-dlp/blob/master/docs/Subtitle.md#auto-translated-subtitles) 分别。有关详细信息,请参见 [#860](https://github.com/yt-dlp/yt-dlp/issues/860) 和 [#12826](https://github.com/yt-dlp/yt-dlp/issues/12826) * `player_client`:用于提取视频数据的客户端。支持的客户端有 `web`、`web_safari`、`web_embedded`、`web_music`、`web_creator`、`mweb`、`ios`、`android`、`android_vr`、`tv`、`tv_downgraded` 和 `tv_simply`。默认情况下,`android_vr,web_safari` 被使用。如果未安装 JavaScript 运行时/引擎,则仅使用 `android_vr`。如果登录了 Cookie,则 `tv_downgraded,web_safari` 用于免费账户,`tv_downgraded,web_creator` 用于高级账户。`web_music` 会在访问 music.youtube.com 时添加(登录 Cookie)。`web_embedded` 会在访问年龄限制视频时添加,但仅在某些情况下有效(如果视频可嵌入),并且可能作为回退添加如果 `android_vr` 无法访问视频。`web_creator` 会在需要账户年龄验证时添加。一些客户端(如 `web_creator` 和 `web_music`)需要 `po_token` 才能下载其格式。某些客户端(如 `web_creator`)仅在使用认证时有效。并非所有客户端都支持通过 Cookie 进行认证。可以使用 `default` 表示默认客户端,或使用 `all` 表示所有客户端(不推荐)。你可以通过在客户端前加 `-` 来排除它,例如 `youtube:player_client=default,-web_safari` * `player_skip`:跳过一些通常需要的网络请求以实现稳健提取。可选值包括 `configs`(跳过客户端配置)、`webpage`(跳过初始网页)、`js`(跳过 JavaScript 播放器)、`initial_data`(跳过初始数据/下一个请求)。虽然这些选项可以减少请求数量或避免某些速率限制,但可能导致格式缺失或元数据错误。详见 [#860](https://github.com/yt-dlp/yt-dlp/issues/860) 和 [#12826](https://github.com/yt-dlp/yt-dlp/issues/12826) * `webpage_skip`:跳过提取嵌入的网页数据。可选值包括 `player_response` 和 `initial_data`。这些选项用于测试,不会跳过任何网络请求。默认不会跳过任何选项;但如果使用了 `player_js_version` 的非 `actual` 值,则隐含 `webpage_skip=player_response` * `webpage_client`:用于网页请求的客户端。选项为 `web` 或 `web_safari`(默认) * `player_params`:YouTube 播放器参数,将覆盖默认参数 * `player_js_variant`:用于 n/sig 解密的播放器 JavaScript 变体。已知变体包括:`main`、`tcc`、`tce`、`es5`、`es6`、`es6_tcc`、`es6_tce`、`tv`、`tv_es6`、`phone`、`house`。默认是 `main`,其他用于调试。你可以使用 `actual` 以使用站点规定的值 * `player_js_version`:用于 n/sig 解密的播放器 JavaScript 版本,格式为 `signature_timestamp@hash`(例如 `20348@0004de42`)。默认是站点规定的版本,可通过 `actual` 选择。使用其他值将隐含 `webpage_skip=player_response` * `comment_sort`:`top` 或 `new`(默认)- 选择评论排序模式(YouTube 侧) * `max_comments`:限制获取的评论数量。逗号分隔的整数列表,表示 `max-comments,max-parents,max-replies,max-replies-per-thread,max-depth`。默认是 `all,all,all,all,all` * `max-depth` 为 `1` 将丢弃所有回复,无论 `max-replies` 或 `max-replies-per-thread` 的值如何 * 例如 `all,all,1000,10,2` 将获取最多 1000 条回复,每条线程最多 10 条回复,且仅 2 层深度(顶级评论及其直接回复)。`1000,all,100` 将获取最多 1000 条评论,最大 100 条回复 * `formats`:更改返回的格式类型。`dashy`(将 HTTP 转换为 DASH)、`duplicate`(内容相同但不同 URL 或协议;包含 `dashy`)、`incomplete`(无法完整下载的直播 DASH、直播自适应 HTTPS 和直播 m3u8)、`missing_pot`(包含需要 PO Token 但缺失的格式) * `innertube_host`:用于所有 API 请求的 Innertube API 主机;例如 `studio.youtube.com`、`youtubei.googleapis.com`。注意从一个子域导出的 Cookie 不能用于其他子域 * `innertube_key`:用于所有 API 请求的 Innertube API 密钥。默认不使用 API 密钥 * `raise_incomplete_data`:`Incomplete Data Received` 抛出错误而不是报告警告 * `data_sync_id`:覆盖用于 Innertube API 请求的账户 Data Sync ID。这在使用 `youtube:player_skip=webpage,configs` 或 `youtubetab:skip=webpage` 时可能需要 * `visitor_data`:覆盖用于 Innertube API 请求的 Visitor Data。这应该与 `player_skip=webpage,configs` 一起使用,并且没有 Cookie。注意:不当使用可能产生不良影响。如果要从浏览器会话使用 Cookie,你应该传递 Cookie(它包含 Visitor ID) * `po_token`:证明来源(PO)令牌列表,格式为 `CLIENT.CONTEXT+PO_TOKEN`,例如 `youtube:po_token=web.gvs+XXX,web.player=XXX,web_safari.gvs+YYY`。上下文可以是 `gvs`(Google 视频服务器 URL)、`player`(Innertube 播放器请求)或 `subs`(字幕)。 * `pot_trace`:启用 PO Token 获取的调试日志记录。`true` 或 `false`(默认) * `fetch_pot`:用于获取 PO Token 的策略。`always`(始终尝试获取 PO Token,无论客户端是否需要)、`never`(从不获取)或 `auto`(默认;仅当客户端需要时获取) * `jsc_trace`:启用 JS 挑战获取的调试日志记录。`true` 或 `false`(默认) * `use_ad_playback_context`:跳过预滚广告以消除强制等待期。不要在向 yt-dlp 传递高级账户 Cookie 时使用此选项,否则会导致高级格式丢失。仅对 `mweb` 和 `web_music` 播放器客户端有效。`true` 或 `false`(默认) #### youtube-ejs * `jitless`:在受支持的 JavaScript 引擎中以无 JIT 模式运行。支持运行时:`deno`、`node` 和 `bun`。提供更好的安全性,但会降低性能/speed。注意 `node` 和 `bun` 仍被认为是不安全的。可以是 `true` 或 `false`(默认) #### youtubepot-webpo * `bind_to_visitor_id`:是否使用 Visitor ID 而非 Visitor Data 进行缓存。`true`(默认)或 `false` #### youtubetab(YouTube 播放列表、频道、订阅源等) * `skip`:一个或多个 `webpage`(跳过初始网页下载)、`authcheck`(允许在未下载初始网页时下载需要认证的播放列表。这可能导致意外行为,请参见 [#1122](https://github.com/yt-dlp/yt-dlp/issues/1122)) * `approximate_date`:提取近似的 `upload_date` 和 `timestamp`。这可能导致基于日期的筛选略有偏差 #### 通用 * `fragment_query`:如果未提供值,则将查询参数透传给 mpd/m3u8 片段 URL,否则应用给定的查询字符串。例如 `fragment_query=VALUE`。不适用于 ffmpeg * `variant_query`:如果未提供值,则将查询参数透传给主 m3u8 URL 的变体播放列表,否则应用给定的查询字符串。例如 `variant_query=VALUE`。不适用于 ffmpeg * `key_query`:如果未提供值,则将查询参数透传给主 m38 URL 的 HLS AES-128 解密密钥 URI,否则应用给定的查询字符串。例如 `key_query=VALUE`。不适用于 ffmpeg * `hls_key`:HLS AES-128 密钥 URI 或密钥(十六进制),可选地加上 IV(十六进制),格式为 `(URI|KEY)[,IV]`;例如 `generic:hls_key=ABCDEF1234567980,0xFEDCBA0987654321`。使用此选项将强制使用本地 HLS 下载器并覆盖 m3u8 播放列表中相应的值 * `is_live`:绕过直播 HLS 检测并手动设置 `live_status` - 值 `false` 将设置为 `not_live`,其他值(或无值)将设置为 `is_live` * `impersonate`: 尝试模拟的初始网页请求目标;例如 `generic:impersonate=safari,chrome-110`。使用 `generic:impersonate` 模拟任意可用目标,使用 `generic:impersonate=false` 禁用模拟(默认) #### vikichannel * `video_types`: 要下载的视频类型 - 可以是 `episodes`、`movies`、`clips`、`trailers` 中的一个或多个 #### youtubewebarchive * `check_all`: 尝试检查更多内容(会消耗更多请求)。可选 `thumbnails`、`captures` #### gamejolt * `comment_sort`: `hot`(默认)、`you`(需要 Cookie)、`top`、`new` - 选择评论排序模式(GameJolt 端) #### hotstar * `res`: 要忽略的分辨率 - 可以是 `sd`、`hd`、`fhd` 中的一个或多个 * `vcodec`: 要忽略的视频编码 - 可以是 `h264`、`h265`、`dvh265` 中的一个或多个 * `dr`: 要忽略的动态范围 - 可以是 `sdr`、`hdr10`、`dv` 中的一个或多个 #### instagram * `app_id`: 用于 API 请求的 `X-IG-App-ID` 头部值。默认为网页应用 ID `936619743392459` #### niconicochannelplus * `max_comments`: 要提取的最大评论数 - 默认是 `120` #### tiktok * `api_hostname`: 用于移动 API 调用的主机名,例如 `api22-normal-c-alisg.tiktokv.com` * `app_name`: 用于移动 API 调用的默认应用名称,例如 `trill` * `app_version`: 用于移动 API 调用的默认应用版本 - 应与 `manifest_app_version` 一同设置,例如 `34.1.2` * `manifest_app_version`: 用于移动 API 调用的默认数字应用版本,例如 `2023401020` * `aid`: 用于移动 API 调用的默认应用 ID,例如 `1180` * `app_info`: 启用移动 API 提取,使用格式为 `/[app_name]/[app_version]/[manifest_app_version]/[aid]` 的一个或多个应用信息字符串,其中 `iid` 是唯一的应用安装 ID。`iid` 是必需值;其他值及其 `/` 分隔符可以省略,例如 `tiktok:app_info=1234567890123456789` 或 `tiktok:app_info=123,456/trill///1180,789//34.0.1/340001` * `device_id`: 启用移动 API 提取,使用一个真实的设备 ID 用于移动 API 调用。默认是随机生成的 19 位字符串 #### rokfinchannel * `tab`: 要下载的标签页 - 可以是 `new`、`top`、`videos`、`podcasts`、`streams`、`stacks` 之一 #### twitter * `api`: 选择用于提取推文的 API - 可以是 `graphql`(默认)、`legacy` 或 `syndication`。登录后无效 #### stacommu, wrestleuniverse * `device_id`: 由网站分配的 UUID 值,用于强制对付费直播内容实施设备限制。可在浏览器本地存储中找到 #### twitch * `client_id`: 要随 GraphQL 请求发送的客户端 ID,例如 `twitch:client_id=kimne78kx3ncx6brgo4mv6wki5h1ko` #### nhkradirulive (NHK らじる★らじる LIVE) * `area`: 要提取的区域版本 - 可以是 `sapporo`、`sendai`、`tokyo`、`nagoya`、`osaka`、`hiroshima`、`matsuyama`、`fukuoka`。默认为 `tokyo` #### nflplusreplay * `type`: 要提取的游戏回放类型 - 可以是 `full_game`、`full_game_spanish`、`condensed_game` 和 `all_22`。可使用 `all` 提取所有可用的回放类型(默认) #### jiocinema * `refresh_token`: 浏览器本地存储中的 `refreshToken` UUID 可用于延长登录会话的生命周期,登录时使用 `token` 作为用户名,`accessToken` 作为密码 #### jiosaavn * `bitrate`: 要请求的音频比特率 - 可以是 `16`、`32`、`64`、`128`、`320`。默认是 `128,320` #### afreecatvlive * `cdn`: 要用于 API 调用以获取流 URL 的一个或多个 CDN ID,例如 `gcp_cdn`、`gs_cdn_pc_app`、`gs_cdn_mobile_web`、`gs_cdn_pc_web` #### soundcloud * `formats`: 从 API 请求时使用的格式。请求的值应为 `{protocol}_{codec}` 格式,例如 `hls_opus,http_aac`。`*` 字符作为通配符使用,例如 `*_mp3`,可单独传递以请求所有格式。已知协议包括 `http`、`hls` 和 `hls-aes`;已知编解码器包括 `aac`、`opus` 和 `mp3`。默认始终提取原始 `download` 格式。默认值为 `http_aac,hls_aac,http_opus,hls_opus,http_mp3,hls_mp3` #### orfon (orf:on) * `prefer_segments_playlist`: 在可用时优先使用节目片段的播放列表,而不是单个完整视频。如需单独获取片段,请使用 `--concat-playlist never --extractor-args "orfon:prefer_segments_playlist"` #### bilibili * `prefer_multi_flv`: 优先提取 FLV 格式而非 MP4,适用于仍提供旧版格式的旧视频 #### sonylivseries * `sort_order`: 系列提取的剧集排序顺序 - 可以是 `asc`(升序,最旧优先)或 `desc`(降序,最新优先)。默认是 `asc` #### tver * `backend`: 提取使用的后端 API - 可以是 `streaks`(默认)或 `brightcove`(已弃用) #### vimeo * `client`: 用于提取视频数据的客户端。可用客户端为 `android`、`ios`、`macos` 和 `web`。仅能使用一个客户端。默认使用 `macos` 客户端,但登录后会使用 `web` 客户端。`web` 客户端仅在使用账户 Cookie 或登录凭据时有效。`android` 和 `ios` 客户端仅在使用之前缓存的 OAuth 令牌时有效 * `original_format_policy`: 提取原始格式的策略 - 可以是 `always`、`never` 或 `auto`。默认 `auto` 策略会尝试避免超过 Web 客户端的 API 速率限制,仅在 Vimeo 公开视频可下载时才发起额外请求 **注意**:这些选项将来可能会更改或移除,无需考虑向后兼容性 # 插件 请注意 **所有** 插件都会被导入,即使未被调用,并且 **不会** 执行任何检查。**使用插件需自行承担风险,请仅使用您信任的代码!** 插件可以是 `` 类型:`extractor` 或 `postprocessor`。 - 提取器插件无需从 CLI 启用,当输入 URL 匹配时会自动调用。 - 提取器插件优先于内置提取器。 - 后处理器插件可通过 `--use-postprocessor NAME` 调用。 插件从命名空间包 `yt_dlp_plugins.extractor` 和 `yt_dlp_plugins.postprocessor` 加载。 换句话说,磁盘上的文件结构大致如下: ``` yt_dlp_plugins/ extractor/ myplugin.py postprocessor/ myplugin.py ``` yt-dlp 会在多个位置查找这些 `yt_dlp_plugins` 命名空间文件夹(详见下文),并从 **所有** 位置加载插件。 可通过设置环境变量 `YTDLP_NO_PLUGINS` 为非空值来完全禁用插件加载。 参见 [Wiki 获取已知插件列表](https://github.com/yt-dlp/yt-dlp/wiki/Plugins) ## 安装插件 插件可通过多种方法和位置安装。 1. **配置**: 插件包(包含 `yt_dlp_plugins` 命名空间文件夹)可放入以下标准 [配置位置](#configuration): * **用户插件** * `${XDG_CONFIG_HOME}/yt-dlp/plugins//yt_dlp_plugins/`(Linux/macOS 推荐) * `${XDG_CONFIG_HOME}/yt-dlp-plugins//yt_dlp_plugins/` * `${APPDATA}/yt-dlp/plugins//yt_dlp_plugins/`(Windows 推荐) * `${APPDATA}/yt-dlp-plugins//yt_dlp_plugins/` * `~/.yt-dlp/plugins//yt_dlp_plugins/` * `~/yt-dlp-plugins//yt_dlp_plugins/` * **系统插件** * `/etc/yt-dlp/plugins//yt_dlp_plugins/` * `/etc/yt-dlp-plugins//yt_dlp_plugins/` 2. **可执行文件位置**:插件包也可安装在可执行文件位置的 `yt-dlp-plugins` 目录下(推荐用于便携安装): * 二进制文件:`/yt-dlp.exe`,`/yt-dlp-plugins//yt_dlp_plugins/` * 源码:`/yt_dlp/__main__.py`,`/yt-dlp-plugins//yt_dlp_plugins/` 3. **pip 及其他位于 `PYTHONPATH` 的位置** * 插件包可通过 `pip` 安装和管理。参见 [yt-dlp-sample-plugins](https://github.com/yt-dlp/yt-dlp-sample-plugins) 获取示例。 * 注意:插件文件在通过 pip 安装的插件包之间必须文件名唯一。 * `PYTHONPATH` 中的任何路径都会搜索 `yt_dlp_plugins` 命名空间文件夹。 * 注意:这不适用于 Pyinstaller 构建。 `.zip`、`.egg` 和 `.whl` 归档文件,只要根目录包含 `yt_dlp_plugins` 命名空间文件夹,也支持作为插件包使用。 * 例如:`${XDG_CONFIG_HOME}/yt-dlp/plugins/mypluginpkg.zip`,其中 `mypluginpkg.zip` 包含 `yt_dlp_plugins//myplugin.py` 运行 yt-dlp 时加上 `--verbose` 可检查插件是否已加载。 ## 开发插件 参见 [yt-dlp-sample-plugins](https://github.com/yt-dlp/yt-dlp-sample-plugins) 获取模板插件包,以及 [Wiki 插件开发指南](https://github.com/yt-dlp/yt-dlp/wiki/Plugin-Development) 获取开发说明。 所有名称以 `IE`/`PP` 结尾的公共类会分别从每个文件中导入用于提取器和后处理器。这遵循下划线前缀规则(例如 `_MyBasePluginIE` 为私有)并尊重 `__all__`。模块也可通过以下划线前缀排除(例如 `_myplugin.py`)。 若要替换现有提取器并使用其子类,请设置 `plugin_name` 类关键字参数(例如 `class MyPluginIE(ABuiltInIE, plugin_name='myplugin')`),这将用 `MyPluginIE` 替换 `ABuiltInIE`。由于提取器已被替换,应通过将其设为私有来避免单独导入子提取器,如上述方法所述。 若您是插件作者,请在仓库中添加 [yt-dlp-plugins](https://github.com/topics/yt-dlp-plugins) 作为主题以提高可发现性。 参见 [开发者说明](https://github.com/yt-dlp/yt-dlp/blob/master/CONTRIBUTING.md#developer-instructions) 了解如何编写和测试提取器。 # 嵌入 yt-dlp yt-dlp 努力成为一个优秀的命令行程序,因此可以从任何编程语言调用。 您的程序应避免解析常规 stdout,因为其可能在将来的版本中更改。相反,应使用 `-J`、`--print`、`--progress-template`、`--exec` 等选项来创建可可靠重现和解析的控制台输出。 从 Python 程序中,您可以更强大地嵌入 yt-dlp,例如: ``` from yt_dlp import YoutubeDL URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] with YoutubeDL() as ydl: ydl.download(URLS) ``` 大多数情况下,您会希望使用各种选项。有关可用选项列表,请查阅 [`yt_dlp/YoutubeDL.py`](yt_dlp/YoutubeDL.py#L183) 或 Python shell 中的 `help(yt_dlp.YoutubeDL)`。如果您已熟悉 CLI,可以使用 [`devscripts/cli_to_api.py`](https://github.com/yt-dlp/yt-dlp/blob/master/devscripts/cli_to_api.py) 将任何 CLI 开关转换为 `YoutubeDL` 参数。 **提示**:如果您是从 youtube-dl 移植代码到 yt-dlp,需要注意的一点是:我们不保证 `YoutubeDL.extract_info` 的返回值是 JSON 可序列化的,甚至不保证是字典。它会是类似字典的对象,但如果需要确保它是可序列化的字典,请按下方 [示例](#embedding-examples) 中的方式将其通过 `YoutubeDL.sanitize_info` 处理。 ## 嵌入示例 #### 提取信息 ``` import json import yt_dlp URL = 'https://www.youtube.com/watch?v=BaW_jenozKc' # ℹ️ See help(yt_dlp.YoutubeDL) for a list of available options and public functions ydl_opts = {} with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(URL, download=False) # ℹ️ ydl.sanitize_info makes the info json-serializable print(json.dumps(ydl.sanitize_info(info))) ``` #### 使用 info-json 下载 ``` import yt_dlp INFO_FILE = 'path/to/video.info.json' with yt_dlp.YoutubeDL() as ydl: error_code = ydl.download_with_info_file(INFO_FILE) print('Some videos failed to download' if error_code else 'All videos successfully downloaded') ``` #### 提取音频 ``` import yt_dlp URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] ydl_opts = { 'format': 'm4a/bestaudio/best', # ℹ️ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments 'postprocessors': [{ # Extract audio using ffmpeg 'key': 'FFmpegExtractAudio', 'preferredcodec': 'm4a', }] } with yt_dlp.YoutubeDL(ydl_opts) as ydl: error_code = ydl.download(URLS) ``` #### 过滤视频 ``` import yt_dlp URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] def longer_than_a_minute(info, *, incomplete): """Download only videos longer than a minute (or with unknown duration)""" duration = info.get('duration') if duration and duration < 60: return 'The video is too short' ydl_opts = { 'match_filter': longer_than_a_minute, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: error_code = ydl.download(URLS) ``` #### 添加日志记录器和进度钩子 ``` import yt_dlp URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] class MyLogger: def debug(self, msg): # For compatibility with youtube-dl, both debug and info are passed into debug # You can distinguish them by the prefix '[debug] ' if msg.startswith('[debug] '): pass else: self.info(msg) def info(self, msg): pass def warning(self, msg): pass def error(self, msg): print(msg) # ℹ️ See "progress_hooks" in help(yt_dlp.YoutubeDL) def my_hook(d): if d['status'] == 'finished': print('Done downloading, now post-processing ...') ydl_opts = { 'logger': MyLogger(), 'progress_hooks': [my_hook], } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download(URLS) ``` #### 添加自定义后处理器 ``` import yt_dlp URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] # ℹ️ See help(yt_dlp.postprocessor.PostProcessor) class MyCustomPP(yt_dlp.postprocessor.PostProcessor): def run(self, info): self.to_screen('Doing stuff') return [], info with yt_dlp.YoutubeDL() as ydl: # ℹ️ "when" can take any value in yt_dlp.utils.POSTPROCESS_WHEN ydl.add_post_processor(MyCustomPP(), when='pre_process') ydl.download(URLS) ``` #### 使用自定义格式选择器 ``` import yt_dlp URLS = ['https://www.youtube.com/watch?v=BaW_jenozKc'] def format_selector(ctx): """ Select the best video and the best audio that won't result in an mkv. NOTE: This is just an example and does not handle all cases """ # formats are already sorted worst to best formats = ctx.get('formats')[::-1] # acodec='none' means there is no audio best_video = next(f for f in formats if f['vcodec'] != 'none' and f['acodec'] == 'none') # find compatible audio extension audio_ext = {'mp4': 'm4a', 'webm': 'webm'}[best_video['ext']] # vcodec='none' means there is no video best_audio = next(f for f in formats if ( f['acodec'] != 'none' and f['vcodec'] == 'none' and f['ext'] == audio_ext)) # These are the minimum required fields for a merged format yield { 'format_id': f'{best_video["format_id"]}+{best_audio["format_id"]}', 'ext': best_video['ext'], 'requested_formats': [best_video, best_audio], # Must be + separated list of protocols 'protocol': f'{best_video["protocol"]}+{best_audio["protocol"]}' } ydl_opts = { 'format': format_selector, } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download(URLS) ``` # 与 YouTube-DL 的差异 ### 新特性 * 基于 [**yt-dlc@f9401f2**](https://github.com/blackjack4494/yt-dlc/commit/f9401f2a91987068139c5f757b12fc711d4c0cee) 并与 [**youtube-dl@a08f2b7**](https://github.com/ytdl-org/youtube-dl/commit/a08f2b7e4567cdc50c0614ee0a4ffdff49b8b6e6) 合并([例外](https://github.com/yt-dlp/yt-dlp/issues/21)) * **[SponsorBlock 集成](#sponsorblock-options)**:可通过 [SponsorBlock](https://sponsor.ajay.app) API 标记/移除 YouTube 视频中的赞助部分 * **[格式排序](#sorting-formats)**:默认格式排序选项已更改,优先选择更高分辨率和更好编解码器而非仅依赖比特率。现在可通过 `-S` 指定排序顺序。这使得格式选择比仅使用 `--format` 更容易([示例](#format-selection-examples))。 * **与 animelover1984/youtube-dl 合并**:获得大部分功能和改进,包括 `--write-comments`、`BiliBiliSearch`、`BilibiliChannel`、在 mp4/ogg/opus 中嵌入缩略图、播放列表 infojson 等。详见 [#31](https://github.com/yt-dlp/yt-dlp/pull/31)。 * **YouTube 改进**: * 支持 Clips、Stories(`ytstories:`)、搜索(包括筛选器)**\***, YouTube Music 搜索、频道专属搜索、搜索前缀(`ytsearch:`)**\***, 合集、订阅源(`:ytfav`、`:ytwatchlater`、`:ytsubs`、`:ythistory`、`:ytrec`、`:ytnotif`) * 针对 [n-sig 限流](https://github.com/ytdl-org/youtube-dl/issues/29326) 的修复 * 使用 `--live-from-start` 下载直播流(*实验性*) * 频道 URL 下载该频道的所有上传内容,包括短片和直播 * **[浏览器 Cookie](https://github.com/yt-dlp/yt-dlp/wiki/Cookies#cookies-from-browser)**:可通过 `--cookies-from-browser BROWSER[+KEYRING][:PROFILE][::CONTAINER]` 自动提取主流浏览器 Cookie * **[下载时间范围](https://github.com/yt-dlp/yt-dlp/wiki/Download-Sections)**:可基于时间戳或章节部分下载视频(`--download-sections`) * **[分章拆分视频](https://github.com/yt-dlp/yt-dlp/wiki/Splitting-Videos-by-Chapters)**:可基于章节将视频拆分为多个文件(`--split-chapters`) * **多线程分片下载**:可并行下载 m3u8/mpd 格式的多个分片。使用 `--concurrent-fragments`(`-N`)设置线程数 * **Aria2c 支持 HLS/DASH**:可将 `aria2c` 用作外部下载器处理 DASH(mpd) 和 HLS(m3u8) 格式 * **新增及修复的提取器**:已添加许多新提取器并修复大量现有提取器。参见 [更新日志](Changelog.md) 或 [支持站点列表](supportedsites.md) * **新 MSO**:Philo、 Spectrum、SlingTV、Cablevision、RCN * **从清单中提取字幕**:可从流媒体清单中提取字幕。详见 [提交记录/be6202f](https://github.com/yt-dlp/yt-dlp/commit/be6202f12b97858b9d716e608394b51065d0419f) * **多路径与输出模板**:可为不同类型文件提供不同的 [输出模板](#output-template) 和下载路径。也可设置临时路径存放中间文件(`--paths`(`-P`)) * **便携配置**:配置文件会自动从主目录和根目录加载。详见 [配置](#configuration) * **输出模板改进**:输出模板现在支持日期时间格式、数字偏移量和对象遍历。详见 [输出模板](#output-template)。更多高级操作可通过 `--parse-metadata` 和 `--replace-in-metadata` 实现 * **其他新选项**:新增大量选项,如 `--alias`、`--print`、`--concat-playlist`、`--wait-for-video`、`--retry-sleep`、`--sleep-requests`、`--convert-thumbnails`、`--force-download-archive`、`--force-overwrites`、`--break-match-filters` 等 * **改进**:正则表达式和 `--format`/`--match-filters` 中的运算符、多个 `--postprocessor-args` 和 `--downloader-args`、更快的存档检查、更多 [格式选择选项](#format-selection)、合并多音频/视频流、多个 `--config-locations`、`--exec` 在不同阶段执行等 * **插件**:提取器和后处理器可从外部文件加载。详见 [插件](#plugins) * **自动更新器**:可通过 `yt-dlp -U` 更新发布版本,使用 `--update-to` 回退到指定版本 * **自动化构建**:[夜间/主构建](#update-channels) 可通过 `--update-to nightly` 和 `--update-to master` 使用 详见 [更新日志](Changelog.md) 或 [提交记录](https://github.com/yt-dlp/yt-dlp/commits) 获取完整变更列表 带 **\*** 的特性已回溯到 youtube-dl ### 默认行为差异 yt-dlp 的部分默认选项与 youtube-dl 和 youtube-dlc 不同: * yt-dlp 仅支持 [Python 3.10+](## "Windows 8"),并将随着版本淘汰逐步停止支持更多版本;而 [youtube-dl 仍支持 Python 2.6+ 和 3.2+](https://github.com/ytdl-org/youtube-dl/issues/30568#issue-1118238743) * 选项 `--auto-number`(`-A`)、`--title`(`-t`)和 `--literal`(`-l`)不再生效。详见 [已移除选项](#Removed) * `avconv` 不被支持作为 `ffmpeg` 的替代 * yt-dlp 的配置存储位置与 youtube-dl 略有不同。详见 [配置](#configuration) * 默认 [输出模板](#output-template) 为 `%(title)s [%(id)s].%(ext)s`。此变更无特殊原因;这是 yt-dlp 发布前就确定的,现在不会改回 `%(title)s-%(id)s.%(ext)s`。可通过 `--compat-options filename` 使用旧行为 * 默认 [格式排序](#sorting-formats) 与 youtube-dl 不同,优先选择更高分辨率和更好编解码器。可使用 `--format-sort` 选项自定义顺序,或使用 `--compat-options format-sort` 使用 youtube-dl 的排序。旧版本 yt-dlp 优先选择 VP9;可通过 `--compat-options prefer-vp9-sort` 回退。两者不可同时使用 * 默认格式选择器为 `bv*+ba/b`。这意味着如果找到比最佳视频-only 格式更好的组合视频+音频格式,会优先选择前者。使用 `-f bv+ba/b` 或 `--compat-options format-spec` 可恢复旧行为 * 与 youtube-dlc 不同,yt-dlp 默认不允许合并多个音频/视频流(因这与 `-f bv*+ba` 冲突)。如需启用,需使用 `--audio-multistreams` 和 `--video-multistreams`。也可使用 `--compat-options multistreams` 恢复两者 * `--no-abort-on-error` 默认启用。使用 `--abort-on-error` 或 `--compat-options abort-on-error` 可改为在出错时中止 * 写入元数据文件(如缩略图、描述或 infojson)时,相同信息也会写入播放列表。使用 `--no-write-playlist-metafiles` 或 `--compat-options no-playlist-metafiles` 可禁止此行为 * 使用 `--add-metadata` 时,`infojson` 会被附加到 `mkv` 文件并同时写入元数据文件。使用 `--no-embed-info-json` 或 `--compat-options no-attach-info-json` 可恢复旧行为 * 某些元数据在使用 `--add-metadata` 时嵌入的字段与 youtube-dl 不同。最显著的是 `comment` 字段包含 `webpage_url`,`synopsis` 包含 `description`。可使用 `--parse-metadata` 修改,或使用 `--compat-options embed-metadata` 恢复 * `playlist_index` 在与 `--playlist-reverse` 和 `--playlist-items` 一起使用时行为不同。详见 [#302](https://github.com/yt-dlp/yt-dlp/issues/302)。可使用 `--compat-options playlist-index` 恢复旧行为 * `-F` 的输出格式已更新。使用 `--compat-options list-formats` 可恢复旧格式 * 直播聊天(如果可用)被视为字幕。使用 `--sub-langs all,-live_chat` 可下载所有字幕(除直播聊天)。也可使用 `--compat-options no-live-chat` 禁止下载任何直播聊天/danmaku * 频道 URL 会下载该频道的所有上传内容,包括短片和直播。如需仅下载特定标签页的视频,请提供该标签页的 URL。若频道未显示请求标签页或没有直播视频,将抛出错误。可使用 `--compat-options no-youtube-channel-redirect` 恢复所有重定向 * YouTube 播放列表会列出不可用视频。使用 `--compat-options no-youtube-unavailable-videos` 可移除此行为 * YouTube 上传的日期为 UTC 时间 * 若使用 `ffmpeg` 作为下载器,格式下载和合并在可能时会合并为单步操作。使用 `--compat-options no-direct-merge` 可恢复旧行为 * 缩略图嵌入到 `mp4` 时尽可能使用 mutagen。如需强制使用 AtomicParsley,请使用 `--compat-options embed-thumbnail-atomicparsley` * 默认情况下,部分内部元数据(如文件名)会从 infojson 中移除。使用 `--no-clean-infojson` 或 `--compat-options no-clean-infojson` 可恢复 * 同时使用 `--embed-subs` 和 `--write-subs` 时,字幕会写入磁盘并嵌入媒体文件。仅使用 `--embed-subs` 会嵌入字幕并自动删除独立文件。详见 [#630(评论)](https://github.com/yt-dlp/yt-dlp/issues/630#issuecomment-893659460)。可使用 `--compat-options no-keep-subs` 恢复旧行为 * `certifi` 将用于 SSL 根证书(如果已安装)。如需使用系统证书(如自签名证书),请使用 `--compat-options no-certifi` * yt-dlp 对文件名中无效字符的清理逻辑与 youtube-dl 不同/更智能。可使用 `--compat-options filename-sanitization` 恢复 youtube-dl 的行为 * ~~yt-dlp 会尝试在可能时将外部下载器输出解析为标准进度输出(当前实现:[aria2c](https://github.com/yt-dlp/yt-dlp/issues/5931))。可使用 `--compat-options no-external-downloader-progress` 以原始格式获取下载器输出~~ * yt-dlp 在 2021.09.01 至 2023.01.02 版本会将 `--match-filters` 应用到嵌套播放列表。这是 [8f18ac](https://github.com/yt-dlp/yt-dlp/commit/8f18aca8717bb0dd49054555af8d386e5eda3a88) 的无意副作用,已在 [d7b460](https://github.com/yt-dlp/yt-dlp/commit/d7b460d0e5fc710950582baed2e3fc616ed98a80) 中修复。可使用 `--compat-options playlist-match-filter` 恢复旧行为 * yt-dlp 在 2021.11.10 至 2023.06.21 期间会对分块/流式格式估算 `filesize_approx`。此功能在 [f2fe69](https://github.com/yt-dlp/yt-dlp/commit/f2fe69c7b0d208bdb1f6292b4ae92bc1e1a7444a) 中添加,因可能极度不准确已在 [0dff8e](https://github.com/yt-dlp/yt-dlp/commit/0dff8e4d1e6e9fb938f4256ea9af7d81f42fd54f) 中移除。可使用 `--compat-options manifest-filesize-approx` 保留估算值 * yt-dlp 使用现代 HTTP 客户端后端(如 `requests`)。可使用 `--compat-options prefer-legacyhttp-handler` 优先使用旧版 HTTP 处理器(`urllib`) * 子模块 `swfinterp`、`casefold` 已被移除 * 使用 `--simulate`(或在 `extract_info` 中设置 `download=False`)不再改变默认格式选择。详见 [#9843](https://github.com/yt-dlp/yt-dlp/issues/9843) * yt-dlp 默认不再对下载文件应用服务器修改时间。使用 `--mtime` 或 `--compat-options mtime-by-default` 可恢复此行为 部分兼容选项别名如下: * `--compat-options all`:启用所有兼容选项(**不要使用此选项!**) * `--compat-options youtube-dl`:等同于 `--compat-options all,-multistreams,-playlist-match-filter,-manifest-filesize-approx,-allow-unsafe-ext,-prefer-vp9-sort` * `--compat-options youtube-dlc`:等同于 `--compat-options all,-no-live-chat,-no-youtube-channel-redirect,-playlist-match-filter,-manifest-filesize-approx,-allow-unsafe-ext,-prefer-vp9-sort` * `--compat-options 2021`:等同于 `--compat-options 2022,no-certifi,filename-sanitization` * `--compat-options 2022`:等同于 `--compat-options 2023,playlist-match-filter,no-external-downloader-progress,prefer-legacy-http-handler,manifest-filesize-approx` * `--compat-options 2023`:等同于 `--compat-options 2024,prefer-vp9-sort` * `--compat-options 2024`:等同于 `--compat-options 2025,mtime-by-default` * `--compat-options 2025`:目前无操作。用于启用未来的兼容选项 使用年度兼容选项别名会将 yt-dlp 的默认行为固定到该日历年末的状态。 以下兼容选项会恢复存在安全漏洞的旧行为: * `--compat-options allow-unsafe-ext`:允许下载任何扩展名(包括不安全扩展)的文件 ([GHSA-79w7-vh3h-8g4j]()) ### 已弃用的选项 以下为所有已弃用的选项及其实现新功能的替代方式: #### 几乎冗余选项 尽管这些选项与新选项几乎相同,但存在差异导致无法完全替代 ``` -j, --dump-json --print "%()j" -F, --list-formats --print formats_table --list-thumbnails --print thumbnails_table --print playlist:thumbnails_table --list-subs --print automatic_captions_table --print subtitles_table ``` #### 冗余选项 尽管这些选项冗余,但因易用性仍建议使用 ``` --get-description --print description --get-duration --print duration_string --get-filename --print filename --get-format --print format --get-id --print id --get-thumbnail --print thumbnail -e, --get-title --print title -g, --get-url --print urls --match-title REGEX --match-filters "title ~= (?i)REGEX" --reject-title REGEX --match-filters "title !~= (?i)REGEX" --min-views COUNT --match-filters "view_count >=? COUNT" --max-views COUNT --match-filters "view_count <=? COUNT" --break-on-reject Use --break-match-filters --user-agent UA --add-headers "User-Agent:UA" --referer URL --add-headers "Referer:URL" --playlist-start NUMBER -I NUMBER: --playlist-end NUMBER -I :NUMBER --playlist-reverse -I ::-1 --no-playlist-reverse Default --no-colors --color no_color ``` #### 不推荐 尽管仍有效,但不建议使用,因为有其他替代方案实现相同效果 ``` --force-generic-extractor --ies generic,default --exec-before-download CMD --exec "before_dl:CMD" --no-exec-before-download --no-exec --all-formats -f all --all-subs --sub-langs all --write-subs --print-json -j --no-simulate --autonumber-size NUMBER Use string formatting, e.g. %(autonumber)03d --autonumber-start NUMBER Use internal field formatting like %(autonumber+NUMBER)s --id -o "%(id)s.%(ext)s" --metadata-from-title FORMAT --parse-metadata "%(title)s:FORMAT" --hls-prefer-native --downloader "m3u8:native" --hls-prefer-ffmpeg --downloader "m3u8:ffmpeg" --list-formats-old --compat-options list-formats (Alias: --no-list-formats-as-table) --list-formats-as-table --compat-options -list-formats [Default] --geo-bypass --xff "default" --no-geo-bypass --xff "never" --geo-bypass-country CODE --xff CODE --geo-bypass-ip-block IP_BLOCK --xff IP_BLOCK ``` #### 开发者选项 这些选项不面向终端用户 ``` --test Download only part of video for testing extractors --load-pages Load pages dumped by --write-pages --allow-unplayable-formats List unplayable formats also --no-allow-unplayable-formats Default ``` #### 旧别名 这些别名不再被记录,原因各异 ``` --clean-infojson --clean-info-json --force-write-download-archive --force-write-archive --no-clean-infojson --no-clean-info-json --no-split-tracks --no-split-chapters --no-write-srt --no-write-subs --prefer-unsecure --prefer-insecure --rate-limit RATE --limit-rate RATE --split-tracks --split-chapters --srt-lang LANGS --sub-langs LANGS --trim-file-names LENGTH --trim-filenames LENGTH --write-srt --write-subs --yes-overwrites --force-overwrites ``` #### Sponskrub 选项 对 [SponSkrub](https://github.com/faissaloo/SponSkrub) 的支持已移除,建议改用 `--sponsorblock` 选项 ``` --sponskrub --sponsorblock-mark all --no-sponskrub --no-sponsorblock --sponskrub-cut --sponsorblock-remove all --no-sponskrub-cut --sponsorblock-remove -all --sponskrub-force Not applicable --no-sponskrub-force Not applicable --sponskrub-location Not applicable --sponskrub-args Not applicable ``` #### 不再支持 这些选项可能无法按预期工作 ``` --prefer-avconv avconv is not officially supported by yt-dlp (Alias: --no-prefer-ffmpeg) --prefer-ffmpeg Default (Alias: --no-prefer-avconv) -C, --call-home Not implemented --no-call-home Default --include-ads No longer supported --no-include-ads Default --write-annotations No supported site has annotations now --no-write-annotations Default --avconv-location Removed alias for --ffmpeg-location --cn-verification-proxy URL Removed alias for --geo-verification-proxy URL --dump-headers Removed alias for --print-traffic --dump-intermediate-pages Removed alias for --dump-pages --youtube-skip-dash-manifest Removed alias for --extractor-args "youtube:skip=dash" (Alias: --no-youtube-include-dash-manifest) --youtube-skip-hls-manifest Removed alias for --extractor-args "youtube:skip=hls" (Alias: --no-youtube-include-hls-manifest) --youtube-include-dash-manifest Default (Alias: --no-youtube-skip-dash-manifest) --youtube-include-hls-manifest Default (Alias: --no-youtube-skip-hls-manifest) --youtube-print-sig-code Removed testing functionality --dump-user-agent No longer supported --xattr-set-filesize No longer supported --compat-options seperate-video-versions No longer needed --compat-options no-youtube-prefer-utc-upload-date No longer supported ``` #### 已移除 这些选项自 2014 年起已被完全移除 # 贡献 参见 [CONTRIBUTING.md](CONTRIBUTING.md#contributing-to-yt-dlp) 了解[提交问题](CONTRIBUTING.md#opening-an-issue) 和[贡献代码](CONTRIBUTING.md#developer-instructions) 的说明 # 维基 参见 [维基](https://github.com/yt-dlp/yt-dlp/wiki) 获取更多信息
标签:FFmpeg, GitHub Actions, pip安装, PyPI, Python, SEO下载, Unlicense, youtube-dl, youtube-dlc, yt-dlp, 下载加速, 二进制发布, 字幕下载, 开源协议, 开源工具, 开源框架, 批量下载, 持续集成, 支持多站, 支持数百个网站, 无后门, 格式转换, 流媒体抓取, 自动笔记, 视频下载器, 逆向工具, 音视频下载, 音频下载器