命令行下载youtube视频, 从YouTube.com和其他视频网站下载视频, python, linux下载youtube (youtube-dl)

 

 

从YouTube.com和其他视频网站下载视频的命令行程序 http://ytdl-org.github.io/youtube-dl/

或者直接下载:youtube-dl

 

安装

要立即为所有UNIX用户(Linux,macOS等)安装它,请键入:

sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl

 

如果你没有curl,你也可以使用最近的wget:

sudo wget https://yt-dl.org/downloads/latest/youtube-dl -O /usr/local/bin/youtube-dl
sudo chmod a+rx /usr/local/bin/youtube-dl

 

Windows用户可以下载一个.exe文件,并将其放置在除了%SYSTEMROOT%\System32的任何PATH位置上(不要放在C:\Windows\System32)。

你也可以用pip:

sudo -H pip install --upgrade youtube-dl

 

如果您已经安装了此命令,则此命令将更新youtube-dl。有关更多信息,请参见pypi页面

macOS用户可以使用Homebrew安装youtube-dl :

brew install youtube-dl

 

或者使用MacPorts

sudo port install youtube-dl

或者,请参阅开发人员有关如何签出和使用git存储库的说明。有关其他选项(包括PGP签名),请参阅youtube-dl下载页面

 

描述

youtube-dl是一个命令行程序,用于从YouTube和更多网站下载视频。它需要Python解释器,版本2.6,2.7或3.2+,并且它不是特定于平台的。它应该适用于你的Unix机器,Windows或macOS。它被发布到公共域,这意味着您可以修改它,重新分发它或者随意使用它。

youtube-dl [OPTIONS] URL [URL...]

 

例如:

# Download best mp4 format available or any other best if no mp4 available
$ youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' youtube-url

# Download best format available but no better than 480p
$ youtube-dl -f 'bestvideo[height<=480]+bestaudio/best[height<=480]' youtube-url

# Download best video only format but no bigger than 50 MB
$ youtube-dl -f 'best[filesize<50M]'  youtube-url

# Download best format available via direct link over HTTP/HTTPS protocol
$ youtube-dl -f '(bestvideo+bestaudio/best)[protocol^=http]' youtube-url

# Download the best video format and the best audio format without merging them
$ youtube-dl -f 'bestvideo,bestaudio' -o '%(title)s.f%(format_id)s.%(ext)s' youtube-url

 

OPTIONS

-h, --help                       Print this help text and exit
--version                        Print program version and exit
-U, --update                     Update this program to latest version. Make
                                 sure that you have sufficient permissions
                                 (run with sudo if needed)
-i, --ignore-errors              Continue on download errors, for example to
                                 skip unavailable videos in a playlist
--abort-on-error                 Abort downloading of further videos (in the
                                 playlist or the command line) if an error
                                 occurs
--dump-user-agent                Display the current browser identification
--list-extractors                List all supported extractors
--extractor-descriptions         Output descriptions of all supported
                                 extractors
--force-generic-extractor        Force extraction to use the generic
                                 extractor
--default-search PREFIX          Use this prefix for unqualified URLs. For
                                 example "gvsearch2:" downloads two videos
                                 from google videos for youtube-dl "large
                                 apple". Use the value "auto" to let
                                 youtube-dl 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                  Do not read configuration files. When given
                                 in the global configuration file
                                 /etc/youtube-dl.conf: Do not read the user
                                 configuration in ~/.config/youtube-
                                 dl/config (%APPDATA%/youtube-dl/config.txt
                                 on Windows)
--config-location PATH           Location of the configuration file; either
                                 the path to the config or its containing
                                 directory.
--flat-playlist                  Do not extract the videos of a playlist,
                                 only list them.
--mark-watched                   Mark videos watched (YouTube only)
--no-mark-watched                Do not mark videos watched (YouTube only)
--no-color                       Do not emit color codes in output

 

网络选项:

--proxy URL                      Use the specified HTTP/HTTPS/SOCKS proxy.
                                 To enable SOCKS proxy, specify a proper
                                 scheme. For example
                                 socks5://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
-4, --force-ipv4                 Make all connections via IPv4
-6, --force-ipv6                 Make all connections via IPv6

 

地理限制:

--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.
--geo-bypass                     Bypass geographic restriction via faking
                                 X-Forwarded-For HTTP header
--no-geo-bypass                  Do not bypass geographic restriction via
                                 faking X-Forwarded-For HTTP header
--geo-bypass-country CODE        Force bypass geographic restriction with
                                 explicitly provided two-letter ISO 3166-2
                                 country code
--geo-bypass-ip-block IP_BLOCK   Force bypass geographic restriction with
                                 explicitly provided IP block in CIDR
                                 notation

 

视频选择:

--playlist-start NUMBER          Playlist video to start at (default is 1)
--playlist-end NUMBER            Playlist video to end at (default is last)
--playlist-items ITEM_SPEC       Playlist video items to download. Specify
                                 indices of the videos in the playlist
                                 separated by commas like: "--playlist-items
                                 1,2,5,8" if you want to download videos
                                 indexed 1, 2, 5, 8 in the playlist. You can
                                 specify range: "--playlist-items
                                 1-3,7,10-13", it will download the videos
                                 at index 1, 2, 3, 7, 10, 11, 12 and 13.
--match-title REGEX              Download only matching titles (regex or
                                 caseless sub-string)
--reject-title REGEX             Skip download for matching titles (regex or
                                 caseless sub-string)
--max-downloads NUMBER           Abort after downloading NUMBER files
--min-filesize SIZE              Do not download any videos smaller than
                                 SIZE (e.g. 50k or 44.6m)
--max-filesize SIZE              Do not download any videos larger than SIZE
                                 (e.g. 50k or 44.6m)
--date DATE                      Download only videos uploaded in this date
--datebefore DATE                Download only videos uploaded on or before
                                 this date (i.e. inclusive)
--dateafter DATE                 Download only videos uploaded on or after
                                 this date (i.e. inclusive)
--min-views COUNT                Do not download any videos with less than
                                 COUNT views
--max-views COUNT                Do not download any videos with more than
                                 COUNT views
--match-filter FILTER            Generic video filter. Specify any key (see
                                 the "OUTPUT TEMPLATE" for a list of
                                 available keys) to match if the key is
                                 present, !key to check if the key is not
                                 present, key > NUMBER (like "comment_count
                                 > 12", also works with >=, <, <=, !=, =) to
                                 compare against a number, key = 'LITERAL'
                                 (like "uploader = 'Mike Smith'", also works
                                 with !=) to match against a string literal
                                 and & to require multiple matches. Values
                                 which are not known are excluded unless you
                                 put a question mark (?) after the operator.
                                 For example, to only match videos that have
                                 been liked more than 100 times and disliked
                                 less than 50 times (or the dislike
                                 functionality is not available at the given
                                 service), but who also have a description,
                                 use --match-filter "like_count > 100 &
                                 dislike_count <? 50 & description" .
--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.
--include-ads                    Download advertisements as well
                                 (experimental)

 

下载选项:

-r, --limit-rate RATE            Maximum download rate in bytes per second
                                 (e.g. 50K or 4.2M)
-R, --retries RETRIES            Number of retries (default is 10), or
                                 "infinite".
--fragment-retries RETRIES       Number of retries for a fragment (default
                                 is 10), or "infinite" (DASH, hlsnative and
                                 ISM)
--skip-unavailable-fragments     Skip unavailable fragments (DASH, hlsnative
                                 and ISM)
--abort-on-unavailable-fragment  Abort downloading when some fragment is not
                                 available
--keep-fragments                 Keep downloaded fragments on disk after
                                 downloading is finished; fragments are
                                 erased by default
--buffer-size SIZE               Size of download buffer (e.g. 1024 or 16K)
                                 (default is 1024)
--no-resize-buffer               Do not automatically adjust the buffer
                                 size. By default, the buffer size is
                                 automatically resized from an initial value
                                 of 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-reverse               Download playlist videos in reverse order
--playlist-random                Download playlist videos in random order
--xattr-set-filesize             Set file xattribute ytdl.filesize with
                                 expected file size
--hls-prefer-native              Use the native HLS downloader instead of
                                 ffmpeg
--hls-prefer-ffmpeg              Use ffmpeg instead of the native HLS
                                 downloader
--hls-use-mpegts                 Use the mpegts container for HLS videos,
                                 allowing to play the video while
                                 downloading (some players may not be able
                                 to play it)
--external-downloader COMMAND    Use the specified external downloader.
                                 Currently supports
                                 aria2c,avconv,axel,curl,ffmpeg,httpie,wget
--external-downloader-args ARGS  Give these arguments to the external
                                 downloader

 

文件系统选项:

-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.
--id                             Use only video ID in file name
-o, --output TEMPLATE            Output filename template, see the "OUTPUT
                                 TEMPLATE" for all the info
--autonumber-start NUMBER        Specify the start value for %(autonumber)s
                                 (default is 1)
--restrict-filenames             Restrict filenames to only ASCII
                                 characters, and avoid "&" and spaces in
                                 filenames
-w, --no-overwrites              Do not overwrite files
-c, --continue                   Force resume of partially downloaded files.
                                 By default, youtube-dl will resume
                                 downloads if possible.
--no-continue                    Do not resume partially downloaded files
                                 (restart from beginning)
--no-part                        Do not use .part files - write directly
                                 into output file
--no-mtime                       Do not use the Last-modified header to set
                                 the file modification time
--write-description              Write video description to a .description
                                 file
--write-info-json                Write video metadata to a .info.json file
--write-annotations              Write video annotations to a
                                 .annotations.xml file
--load-info-json FILE            JSON file containing the video information
                                 (created with the "--write-info-json"
                                 option)
--cookies FILE                   File to read cookies from and dump cookie
                                 jar in
--cache-dir DIR                  Location in the filesystem where youtube-dl
                                 can store some downloaded information
                                 permanently. By default
                                 $XDG_CACHE_HOME/youtube-dl or
                                 ~/.cache/youtube-dl . At the moment, only
                                 YouTube player files (for videos with
                                 obfuscated signatures) are cached, but that
                                 may change.
--no-cache-dir                   Disable filesystem caching
--rm-cache-dir                   Delete all filesystem cache files

 

缩略图:

--write-thumbnail                Write thumbnail image to disk
--write-all-thumbnails           Write all thumbnail image formats to disk
--list-thumbnails                Simulate and list all available thumbnail
                                 formats

 

详细程度/模拟选项:

-q, --quiet                      Activate quiet mode
--no-warnings                    Ignore warnings
-s, --simulate                   Do not download the video and do not write
                                 anything to disk
--skip-download                  Do not download the video
-g, --get-url                    Simulate, quiet but print URL
-e, --get-title                  Simulate, quiet but print title
--get-id                         Simulate, quiet but print id
--get-thumbnail                  Simulate, quiet but print thumbnail URL
--get-description                Simulate, quiet but print video description
--get-duration                   Simulate, quiet but print video length
--get-filename                   Simulate, quiet but print output filename
--get-format                     Simulate, quiet but print output format
-j, --dump-json                  Simulate, quiet but print JSON information.
                                 See the "OUTPUT TEMPLATE" for a description
                                 of available keys.
-J, --dump-single-json           Simulate, quiet but print JSON information
                                 for each command-line argument. If the URL
                                 refers to a playlist, dump the whole
                                 playlist information in a single line.
--print-json                     Be quiet and print the video information as
                                 JSON (video is still being downloaded).
--newline                        Output progress bar as new lines
--no-progress                    Do not print progress bar
--console-title                  Display progress in console titlebar
-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
-C, --call-home                  Contact the youtube-dl server for debugging
--no-call-home                   Do NOT contact the youtube-dl server for
                                 debugging

 

解决方法:

--encoding ENCODING              Force the specified encoding (experimental)
--no-check-certificate           Suppress HTTPS certificate validation
--prefer-insecure                Use an unencrypted connection to retrieve
                                 information about the video. (Currently
                                 supported only for YouTube)
--user-agent UA                  Specify a custom user agent
--referer URL                    Specify a custom referer, use if the video
                                 access is restricted to one domain
--add-header 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-interval SECONDS         Number of seconds to sleep before each
                                 download when used alone or a lower bound
                                 of a range for randomized sleep before each
                                 download (minimum possible number of
                                 seconds to sleep) when used along with
                                 --max-sleep-interval.
--max-sleep-interval SECONDS     Upper bound of a range for randomized sleep
                                 before each download (maximum possible
                                 number of seconds to sleep). Must only be
                                 used along with --min-sleep-interval.

 

视频格式选项:

-f, --format FORMAT              Video format code, see the "FORMAT
                                 SELECTION" for all the info
--all-formats                    Download all available video formats
--prefer-free-formats            Prefer free video formats unless a specific
                                 one is requested
-F, --list-formats               List all available formats of requested
                                 videos
--youtube-skip-dash-manifest     Do not download the DASH manifests and
                                 related data on YouTube videos
--merge-output-format FORMAT     If a merge is required (e.g.
                                 bestvideo+bestaudio), output to given
                                 container format. One of mkv, mp4, ogg,
                                 webm, flv. Ignored if no merge is required

 

字幕选项:

--write-sub                      Write subtitle file
--write-auto-sub                 Write automatically generated subtitle file
                                 (YouTube only)
--all-subs                       Download all the available subtitles of the
                                 video
--list-subs                      List all available subtitles for the video
--sub-format FORMAT              Subtitle format, accepts formats
                                 preference, for example: "srt" or
                                 "ass/srt/best"
--sub-lang LANGS                 Languages of the subtitles to download
                                 (optional) separated by commas, use --list-
                                 subs for available language tags

 

验证选项:

-u, --username USERNAME          Login with this account ID
-p, --password PASSWORD          Account password. If this option is left
                                 out, youtube-dl will ask interactively.
-2, --twofactor TWOFACTOR        Two-factor authentication code
-n, --netrc                      Use .netrc authentication data
--video-password PASSWORD        Video password (vimeo, smotri, youku)

 

Adobe Pass选项:

--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, youtube-dl will
                                 ask interactively.
--ap-list-mso                    List all supported multiple-system
                                 operators

 

后处理选项:

-x, --extract-audio              Convert video files to audio-only files
                                 (requires ffmpeg or avconv and ffprobe or
                                 avprobe)
--audio-format FORMAT            Specify audio format: "best", "aac",
                                 "flac", "mp3", "m4a", "opus", "vorbis", or
                                 "wav"; "best" by default; No effect without
                                 -x
--audio-quality QUALITY          Specify ffmpeg/avconv audio quality, insert
                                 a value between 0 (better) and 9 (worse)
                                 for VBR or a specific bitrate like 128K
                                 (default 5)
--recode-video FORMAT            Encode the video to another format if
                                 necessary (currently supported:
                                 mp4|flv|ogg|webm|mkv|avi)
--postprocessor-args ARGS        Give these arguments to the postprocessor
-k, --keep-video                 Keep the video file on disk after the post-
                                 processing; the video is erased by default
--no-post-overwrites             Do not overwrite post-processed files; the
                                 post-processed files are overwritten by
                                 default
--embed-subs                     Embed subtitles in the video (only for mp4,
                                 webm and mkv videos)
--embed-thumbnail                Embed thumbnail in the audio as cover art
--add-metadata                   Write metadata to the video file
--metadata-from-title FORMAT     Parse additional metadata like song title /
                                 artist from the video title. The format
                                 syntax is the same as --output. Regular
                                 expression with named capture groups may
                                 also be used. The parsed parameters replace
                                 existing values. Example: --metadata-from-
                                 title "%(artist)s - %(title)s" matches a
                                 title like "Coldplay - Paradise". Example
                                 (regex): --metadata-from-title
                                 "(?P<artist>.+?) - (?P<title>.+)"
--xattrs                         Write metadata to the video file's xattrs
                                 (using dublin core and xdg standards)
--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 file if we can, warn
                                 otherwise)
--prefer-avconv                  Prefer avconv over ffmpeg for running the
                                 postprocessors
--prefer-ffmpeg                  Prefer ffmpeg over avconv for running the
                                 postprocessors (default)
--ffmpeg-location PATH           Location of the ffmpeg/avconv binary;
                                 either the path to the binary or its
                                 containing directory.
--exec CMD                       Execute a command on the file after
                                 downloading, similar to find's -exec
                                 syntax. Example: --exec 'adb push {}
                                 /sdcard/Music/ && rm {}'
--convert-subs FORMAT            Convert the subtitles to other format
                                 (currently supported: srt|ass|vtt|lrc)

输出模板

-o选项允许用户指示输出文件名的模板。

tl; dr: 导航我的例子

下载单个文件时的基本用法是不设置任何模板参数,例如youtube-dl -o funny_video.flv "https://some/video"。但是,它可能包含在下载每个视频时将被替换的特殊序列。可以根据python字符串格式化操作来格式化特殊序列。例如,%(NAME)s%(NAME)05d。为了澄清,这是一个百分号,后跟括号中的名称,后跟格式化操作。允许的名称和序列类型是:

  • id (字符串):视频标识符
  • title (字符串):视频标题
  • url (字符串):视频网址
  • ext (字符串):视频文件扩展名
  • alt_title (字符串):视频的次要标题
  • display_id (字符串):视频的替代标识符
  • uploader (字符串):视频上传者的全名
  • license (字符串):视频许可的许可证名称
  • creator (字符串):视频的创建者
  • release_date (字符串):视频发布时的日期(YYYYMMDD)
  • timestamp (数字):视频可用时的UNIX时间戳
  • upload_date (字符串):视频上传日期(YYYYMMDD)
  • uploader_id (字符串):视频上传者的昵称或ID
  • channel (字符串):视频上传频道的全名
  • channel_id (字符串):频道的ID
  • location (字符串):拍摄视频的实际位置
  • duration (数字):视频的长度,以秒为单位
  • view_count (数字):有多少用户在平台上观看了视频
  • like_count (数字):视频的正评分数
  • dislike_count (数字):视频的负面评分数
  • repost_count (数字):视频的重新发布次数
  • average_rating (数字):用户给出的平均评分,使用的比例取决于网页
  • comment_count (数字):视频的评论数量
  • age_limit (数字):视频的年龄限制(年)
  • is_live (布尔值):此视频是直播视频还是固定长度视频
  • start_time (数字):应在URL中指定的再现应开始的时间(以秒为单位)
  • end_time (数字):复制应结束的时间(以秒为单位),如URL中所指定
  • format (字符串):格式的人类可读描述
  • format_id (字符串):由。指定的格式代码 --format
  • format_note (字符串):有关格式的其他信息
  • width (数字):视频的宽度
  • height (数字):视频的高度
  • resolution (字符串):宽度和高度的文字说明
  • tbr (数字):以KBit / s为单位的音频和视频的平均比特率
  • abr (数字):平均音频比特率,单位为KBit / s
  • acodec (字符串):正在使用的音频编解码器的名称
  • asr (数字):以赫兹为单位的音频采样率
  • vbr (数字):平均视频比特率,单位为KBit / s
  • fps (数字):帧速率
  • vcodec (字符串):正在使用的视频编解码器的名称
  • container (字符串):容器格式的名称
  • filesize (数字):字节数,如果事先知道的话
  • filesize_approx (数字):字节数的估计值
  • protocol (字符串):将用于实际下载的协议
  • extractor (字符串):提取器的名称
  • extractor_key (字符串):提取器的键名
  • epoch (数字):创建文件时的Unix纪元
  • autonumber (数字):每次下载时将增加的五位数字,从零开始
  • playlist (字符串):包含视频的播放列表的名称或ID
  • playlist_index (数字):播放列表中的视频索引根据播放列表的总长度填充前导零
  • playlist_id (字符串):播放列表标识符
  • playlist_title (字符串):播放列表标题
  • playlist_uploader (字符串):播放列表上传者的全名
  • playlist_uploader_id (字符串):播放列表上传者的昵称或ID

适用于属于某个逻辑章节或部分的视频:

  • chapter (字符串):视频所属章节的名称或标题
  • chapter_number (数字):视频所属章节的编号
  • chapter_id (字符串):视频所属章节的ID

适用于某些系列或节目的剧集视频:

  • series (字符串):视频剧集所属系列或节目的标题
  • season (字符串):视频剧集所属季节的标题
  • season_number (数字):视频剧集所属的季节数
  • season_id (字符串):视频剧集所属季节的ID
  • episode (字符串):视频剧集的标题
  • episode_number (数字):一季内视频集的编号
  • episode_id (字符串):视频集的ID

适用于作为曲目或音乐专辑的一部分的媒体:

  • track (字符串):曲目的标题
  • track_number (数字):专辑或光盘中的曲目编号
  • track_id (字符串):轨道的ID
  • artist (字符串):曲目的艺术家
  • genre (字符串):曲目的流派
  • album (字符串):曲目所属专辑的标题
  • album_type (字符串):专辑的类型
  • album_artist (字符串):所有艺术家的名单出现在专辑中
  • disc_number (数字):轨道所属的光盘或其他物理介质的编号
  • release_year (数字):专辑发行时的年份(YYYY)

当在输出模板中引用时,每个上述序列将被对应于序列名称的实际值替换。请注意,某些序列不能保证存在,因为它们依赖于特定提取器获得的元数据。这些序列将被替换NA

例如,对于-o %(title)s-%(id)s.%(ext)s带有标题youtube-dl test video和id 的mp4视频BaW_jenozKcj,这将导致在youtube-dl test video-BaW_jenozKcj.mp4当前目录中创建一个文件。

对于数字序列,您可以使用与数字相关的格式,例如,%(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标志以获得更短的标题:

输出模板和Windows批处理文件

如果您在Windows批处理文件中使用输出模板,则必须%通过加倍来转义普通百分比字符(),这样-o "%(title)s-%(id)s.%(ext)s"才能成为-o "%%(title)s-%%(id)s.%%(ext)s"。但是你不应该触摸%不是普通字符的,例如扩展的环境变量应保持不变:-o "C:\%HOMEPATH%\Desktop\%%(title)s.%%(ext)s"

输出模板示例

请注意,在Windows上,您可能需要使用双引号而不是单引号。

$ youtube-dl --get-filename -o '%(title)s.%(ext)s' BaW_jenozKc
youtube-dl test video ''_ä↭?.mp4    # All kinds of weird characters

$ youtube-dl --get-filename -o '%(title)s.%(ext)s' BaW_jenozKc --restrict-filenames
youtube-dl_test_video_.mp4          # A simple file name

# Download YouTube playlist videos in separate directory indexed by video order in a playlist
$ youtube-dl -o '%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s' https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re

# Download all playlists of YouTube channel/user keeping each playlist in separate directory:
$ youtube-dl -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
$ youtube-dl -u user -p password -o '~/MyVideos/%(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
$ youtube-dl -o "C:/MyVideos/%(series)s/%(season_number)s - %(season)s/%(episode_number)s - %(episode)s.%(ext)s" https://videomore.ru/kino_v_detalayah/5_sezon/367617

# Stream the video being downloaded to stdout
$ youtube-dl -o - BaW_jenozKc

 

 

格式选择

默认情况下,youtube-dl会尝试下载最佳可用质量,即如果你想要最好的质量,你不需要传递任何特殊选项,youtube-dl 默认会为你猜测。

但有时您可能希望以不同的格式下载,例如当您处于慢速或间歇性连接时。实现这一目标的关键机制是所谓的格式选择,您可以根据该格式明确指定所需的格式,根据某些标准或标准选择格式,设置优先级等等。

格式选择的一般语法是--format FORMAT或更短-f FORMAT,其中FORMAT选择器表达式,即描述您要下载的格式或格式的表达式。

tl; dr: 导航我的例子

最简单的情况是请求特定格式,例如,-f 22您可以下载格式代码等于22的格式。您可以使用--list-formats或获取特定视频的可用格式代码列表-F。请注意,这些格式代码是特定于提取器的。

你也可以使用一个文件扩展名(目前3gpaacflvm4amp3mp4oggwavwebm都支持),下载特定文件扩展名担任一个单一的文件,如质量最好的格式,-f webm将下载与最优质的格式webm扩展名担任了单个文件。

您还可以使用特殊名称来选择特定的边缘大小写格式:

  • best:选择具有视频和音频的单个文件所代表的最佳质量格式。
  • worst:选择具有视频和音频的单个文件所代表的最差质量格式。
  • bestvideo:选择最佳质量的仅视频格式(例如DASH视频)。可能无法使用。
  • worstvideo:选择质量最差的纯视频格式。可能无法使用。
  • bestaudio:选择质量最佳的音频格式。可能无法使用。
  • worstaudio:选择质量最差的音频格式。可能无法使用。

例如,要下载可以使用的最差质量视频格式-f worstvideo

如果您要下载多个视频并且它们没有相同的格式,您可以使用斜杠指定首选项顺序。请注意,斜杠是左关联的,即左侧的格式是首选,例如,-f 22/17/18如果可用则下载格式22,否则它将下载格式17(如果可用),否则它将下载格式18(如果可用),否则它会抱怨没有合适的格式可供下载。

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

您还可以通过将条件放在括号中来过滤视频格式,如-f "best[height=720]"(或-f "[filesize>10M]")中所示。

下面的数值元字段可以用比较使用<<=>>==(等于), !=(未等于):

  • filesize:字节数,如果事先知道的话
  • width:视频宽度(如果已知)
  • height:视频的高度,如果已知
  • tbr:以KBit / s为单位的音频和视频的平均比特率
  • abr:平均音频比特率(KBit / s)
  • vbr:平均视频比特率(KBit / s)
  • asr:以赫兹为单位的音频采样率
  • fps:帧率

还过滤比较=(等于),^=(开头),$=(结束),*=(包含)和跟随字符串元字段的工作:

  • ext: 文件扩展名
  • acodec:正在使用的音频编解码器的名称
  • vcodec:正在使用的视频编解码器的名称
  • container:容器格式的名称
  • protocol:将被用于实际下载协议,小写(httphttpsrtsprtmprtmpemmsf4mismhttp_dash_segmentsm3u8,或m3u8_native
  • format_id:格式的简短描述

任何字符串比较都可以以否定为前缀,!以产生相反的比较,例如!*=(不包含)。

注意,保证上述元字段都不存在,因为这仅取决于由特定提取器获得的元数据,即视频主机提供的元数据。

除非您?在运算符后面添加问号(),否则将排除值未知的格式。您可以组合格式过滤器,因此-f "[height <=? 720][tbr>500]"选择最多720p视频(或高度未知的视频),比特率至少为500 KBit / s。

您可以使用-f <video-format>+<audio-format>(需要安装ffmpeg或avconv)-f bestvideo+bestaudio将两种格式的视频和音频合并为一个文件,例如,将下载最佳的纯视频格式,最佳纯音频格式,并将它们与ffmpeg / avconv一起复用。

格式选择器也可以使用括号进行分组,例如,如果要下载高度低于480的最佳mp4和webm格式,则可以使用-f '(mp4,webm)[height<480]'

自2015年4月底和版本2015.04.26起,youtube-dl将使用-f bestvideo+bestaudio/best默认格式选择(请参阅#5447#5456)。如果安装了ffmpeg或avconv,则会导致下载bestvideobestaudio单独下载并将它们复合到一个文件中,从而提供最佳的整体质量。否则它会回退best并导致下载作为单个文件提供的最佳可用质量。best对于不是来自YouTube的视频也需要,因为它们不提供两个不同文件中的音频和视频。如果您只想下载一些DASH格式(例如,如果您对获取分辨率高于1080p的视频不感兴趣),可以添加-f bestvideo[height<=?1080]+bestaudio/best到您的配置文件。请注意,如果您使用youtube-dl流式传输stdout(并且最有可能将其传输到您的媒体播放器),即您明确指定输出模板为-o -,youtube-dl仍然使用-f best格式选择,以便立即开始向播放器传送内容而不是等到,bestvideobestaudio下载和多路复用。

如果您想保留旧的格式选择行为(在youtube-dl 2015.04.26之前),即您希望下载作为单个文件提供的最佳可用质量媒体,则应明确指定您的选择-f best。您可能希望将其添加到配置文件中,以便每次运行youtube-dl时都不键入它。

格式选择示例

请注意,在Windows上,您可能需要使用双引号而不是单引号。

# Download best mp4 format available or any other best if no mp4 available
$ youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best'

# Download best format available but no better than 480p
$ youtube-dl -f 'bestvideo[height<=480]+bestaudio/best[height<=480]'

# Download best video only format but no bigger than 50 MB
$ youtube-dl -f 'best[filesize<50M]'

# Download best format available via direct link over HTTP/HTTPS protocol
$ youtube-dl -f '(bestvideo+bestaudio/best)[protocol^=http]'

# Download the best video format and the best audio format without merging them
$ youtube-dl -f 'bestvideo,bestaudio' -o '%(title)s.f%(format_id)s.%(ext)s'

 

请注意,在最后一个示例中,建议输出模板作为bestvideo,bestaudio可能具有相同的文件名。

视频选择

可以使用选项按照上传日期过滤视频--date--datebefore--dateafter。他们接受两种格式的日期:

  • 绝对日期:格式的日期YYYYMMDD
  • 相对日期:格式的日期 (now|today)[+-][0-9](day|week|month|year)(s)?

例子:

#仅下载过去6个月内上传的视频 
$ youtube-dl --dateafter now-6months#仅下载1970年1月1日上传的视频 
$ youtube-dl  - 日期19700101
$#仅下载200x上传的视频十年 
$ youtube-dl --dateafter 20000101 --datebefore 20091231

 

更多参考github:https://github.com/ytdl-org/youtube-dl

 

 

本文:命令行下载youtube视频, 从YouTube.com和其他视频网站下载视频, python, linux下载youtube (youtube-dl)

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.