youtube-dl – 从youtube.com或其他视频平台下载视频
安装
要立即为所有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
如果您没有crul,您也可以使用最近的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文件并将其放置在PATH上的任何位置,但%SYSTEMROOT%\System32
(例如,不要放入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.com和其他几个网站下载视频。它需要Python解释器,版本2.6、2.7或3.2+,并且它不是特定于平台的。它应该可以在Unix盒子、Windows或macOS上工作。它被发布到公共领域,这意味着您可以修改、重新分发或随意使用它。
youtube-dl [OPTIONS] URL [URL...]
选项
-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
年龄限制:
利用导出youtube登陆之后的cookie,来完美解决成人内容视频下载限制。这个需要一个小插件 Get Cookie,该插件可以登录youtube后导出cookie,并命名为youtube.com_cookies.txt存到本地,记得在指令行用绝对路径调用cookies,当然如果你的cookie就在当前节点,那就可以不用路径。
在Github里面有人讨论用-u,-p的办法登录youtube,实际上行不通, 因为youtube不支持这种指令登录。
--cookies YOUR-COOKIE use the download directory to save the cookie in Documents #how to use ? please note use the absolute path for cookies #if you are not save cookie in current download folder example: youtube-dl --cookies ~/Documents/youtube.com_cookies.txt [YouTube URL]
视频选择:
--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,c url,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 --output-na-placeholder PLACEHOLDER Placeholder value for unavailable meta fields in output filename template (default is "NA") --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 (cookie can be extracted while contents website logged 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, 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/avconv and ffprobe/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 and post-processing, 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)
配置
您可以通过将任何受支持的命令行选项放置到配置文件中来配置youtube-dl。在Linux和macOS上,系统范围的配置文件位于/etc/youtube-dl.conf
,用户范围的配置文件位于~/.config/youtube-dl/config
。在Windows上,用户范围的配置文件位置为%APPDATA%\youtube-dl\config.txt
或C:\Users\<user name>\youtube-dl.conf
。请注意,默认情况下,配置文件可能不存在,因此您可能需要自己创建。
例如,使用以下配置文件,youtube-dl将始终提取音频,而不是复制mtime,使用代理并将所有视频保存在Movies
目录下,并保存在主目录中:
# Lines starting with # are comments # Always extract audio -x # Do not copy the mtime --no-mtime # Use this proxy --proxy 127.0.0.1:3128 # Save all videos under Movies directory in your home directory -o ~/Movies/%(title)s.%(ext)s
请注意,配置文件中的选项与常规命令行调用中使用的选项(又名开关)相同,因此在-
或--
之后必须没有空格,例如-o
或--proxy
,但不是- o
或-- proxy
。
You can use --ignore-config
if you want to disable the configuration file for a particular youtube-dl run.
You can also use --config-location
if you want to use custom configuration file for a particular youtube-dl run.
使用.netrc
文件进行身份验证
您可能还想为支持身份验证的提取器配置自动凭据存储(通过提供带有--username
和--password
登录和密码),以便不将凭据作为每次youtube-dl执行的命令行参数传递,并防止跟踪shell命令历史记录中的纯文本密码。您可以在每个提取器的基础上使用.netrc
文件来实现这一点。为此,您需要在$HOME
中创建一个.netrc
文件,并限制仅由您读取/写入的权限:
touch $HOME/.netrc chmod a-rwx,u+rw $HOME/.netrc
之后,您可以以以下格式添加提取器的凭据,其中提取器是小写提取器的名称:
machine <extractor> login <login> password <password>
例如:
machine youtube login myaccount@gmail.com password my_youtube_password machine twitch login my_twitch_account_name password my_twitch_password
要激活.netrc
文件的身份验证,您应该将--netrc
传递给youtube-dl或将其放入配置文件中。
在Windows上,您可能还需要手动设置%HOME%
环境变量。例如:
set HOME=%USERPROFILE%
输出模板
-o
选项允许用户为输出文件名指示模板。
tl;dr:引导我查看示例。
基本用法是在下载单个文件时不设置任何模板参数,例如在youtube-dl -o funny_video.flv "https://some/video"
然而,它可能包含特殊序列,将在下载每个视频时替换。特殊序列可以根据python字符串格式化操作进行格式化。例如,%(NAME)s
或%(NAME)05d
。为了澄清,这是一个百分比符号,括号中后跟一个名称,然后是格式化操作。允许的名称和序列类型是:
id
(字符串):视频标识符title
(字符串):视频标题url
(字符串):视频URLext
(字符串):视频文件扩展名alt_title
(字符串):视频的次要标题display_id
(字符串):视频的替代标识符uploader
(字符串):视频上传器的全名license
(字符串):视频的许可名称creator
(字符串):视频的创建者release_date
(字符串):视频发布日期(YYYYMMDD)timestamp
(数字):视频可用时的UNIX时间戳upload_date
(字符串):视频上传日期(YYYYMMDD)uploader_id
(字符串):视频上传者的昵称或IDchannel
(字符串):视频上传频道的全名channel_id
(字符串):频道的IDlocation
(字符串):拍摄视频的物理位置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
(数字):每次下载时会增加的数量,从--autonumber-start
playlist
(字符串):包含视频的播放列表的名称或IDplaylist_index
(数字):播放列表中的视频索引根据播放列表的总长度填充了前导零playlist_id
(字符串):播放列表标识符playlist_title
(字符串):播放列表标题playlist_uploader
(字符串):播放列表上传器的全名playlist_uploader_id
(字符串):播放列表上传器的昵称或ID
适用于属于某些逻辑章节或章节的视频:
chapter
(字符串):视频所属章节的名称或标题chapter_number
(数字):视频所属章节的编号chapter_id
(字符串):视频所属章节的ID
适用于某些系列或节目的一集视频:
series
(字符串):视频剧集所属的系列或节目的标题season
(字符串):视频剧集所属的本季标题season_number
(数字):视频剧集所属的季节数量season_id
(字符串):视频剧集所属的本季IDepisode
(字符串):视频集的标题episode_number
(数字):一季内的视频剧集数量episode_id
(字符串):视频集的ID
适用于曲目或音乐专辑的一部分的媒体:
track
(字符串):轨道的标题track_number
(数字):专辑或光盘中的曲目数量track_id
(字符串):轨道的IDartist
(弦):曲目的艺术家genre
(字符串):轨道的类型album
(字符串):曲目所属专辑的标题album_type
(字符串):专辑类型album_artist
(字符串):专辑中出现的所有艺术家的列表disc_number
(数字):轨道所属的光盘或其他物理介质的数量release_year
(数字):专辑发行年份(YYYYY)
在输出模板中引用的每个上述序列将被与序列名称相对应的实际值所取代。请注意,一些序列不能保证存在,因为它们取决于特定提取器获得的元数据。此类序列将被--output-na-placeholder
(默认为NA
提供的占位符值所取代。
例如,对于-o %(title)s-%(id)s.%(ext)s
和标题为youtube-dl test video
和id BaW_jenozKcj
mp4视频,这将导致在当前目录中创建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
。
在某些情况下,您不希望特殊字符,如中、空格或&,例如通过8位不安全通道将下载的文件名传输到Windows系统或文件名时。在这些情况下,添加--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
或shorter -f FORMAT
,其中FORMAT
是选择器表达式,即描述要下载的格式的表达式。
tl;dr:引导我查看示例。
The simplest case is requesting a specific format, for example with -f 22
you can download the format with format code equal to 22. You can get the list of available format codes for particular video using --list-formats
or -F
. Note that these format codes are extractor specific.
您还可以使用文件扩展名(目前支持3gp
、aac
、flv
、m4a
、mp3
、mp4
、ogg
、wav
、webm
)下载作为单个文件的特定文件扩展名的最佳质量格式,例如-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]"
。
The following numeric meta fields can be used with comparisons <
, <=
, >
, >=
, =
(equals), !=
(not equals):
filesize
:字节数,如果提前知道的话width
:视频宽度(如果已知)height
:视频的高度,如果已知tbr
:音频和视频的平均比特率(KBit/s)abr
:KBit/s的平均音频比特率vbr
:KBit/s的平均视频比特率asr
:赫兹的音频采样率fps
:帧速率
还过滤比较=
(等于)、^=
(从开始)、$=
(以)、*=
(包含)和以下字符串元字段进行筛选:
ext
:文件扩展名acodec
:使用的音频编解码器名称vcodec
:使用中的视频编解码器名称container
:容器格式的名称protocol
:用于实际下载的小写协议(http
、https
、rtsp
、rtmp
、rtmpe
、mms
、f4m
、ism
、http_dash_segments
、m3u8
或m3u8_native
)format_id
:格式的简短描述language
:语言代码
任何字符串比较都可以以否定为前缀!
为了产生相反的比较,例如!*=
(不包含)。
请注意,上述任何元字段都不能保证存在,因为这完全取决于特定提取器获得的元数据,即视频主机提供的元数据。
Formats for which the value is not known are excluded unless you put a question mark (?
) after the operator. You can combine format filters, so -f "[height <=? 720][tbr>500]"
selects up to 720p videos (or videos where the height is not known) with a bitrate of at least 500 KBit/s.
您可以使用-f <video-format>+<audio-format>
(需要安装ffmpeg或avconvconv)将两种格式的视频和音频合并到单个文件中,例如-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,则可以分别下载bestvideo
和bestaudio
,并将它们合并到一个文件中,以获得最佳的整体质量。否则,它会回到best
,并导致将可用质量下载为单个文件的最佳质量。对于不来自YouTube的视频,也需要best
,因为它们没有在两个不同的文件中提供音频和视频。如果您只想下载一些DASH格式(例如,如果您对获得分辨率高于1080p的视频不感兴趣),您可以添加-f bestvideo[height<=?1080]+bestaudio/best
到您的配置文件。请注意,如果您使用youtube-dl流式传输到stdout
(然后最有可能将其传输到您的媒体播放器),即您明确指定输出模板as-o -
,youtube-dl仍然使用-f best
格式选择,以便立即开始向播放器交付内容,而不是等到bestvideo
和bestaudio
下载并静音。
如果您想保留旧格式选择行为(在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)?
示例:
# Download only the videos uploaded in the last 6 months $ youtube-dl --dateafter now-6months # Download only the videos uploaded on January 1, 1970 $ youtube-dl --date 19700101 $ # Download only the videos uploaded in the 200x decade $ youtube-dl --dateafter 20000101 --datebefore 20091231
常见问题解答
如何更新youtube-dl?
如果您遵循了我们的手动安装说明,您只需运行youtube-dl -U
(或者在Linux上运行sudo youtube-dl -U
)。
如果您使用过pip,一个简单的sudo pip install -U youtube-dl
就足够更新了。
如果您使用apt-get或yum等软件包管理器安装了youtube-dl,请使用标准系统更新机制进行更新。请注意,分发包通常已过时。根据经验,youtube-dl每月至少发布一次,通常每周甚至每天发布一次。只需访问https://yt-dl.org即可了解当前版本。不幸的是,如果您的发行版服务于一个非常过时的版本,我们youtube-dl开发人员无能为力。您可以(也应该)在他们的bugtracker或支持论坛中向您的发行版投诉。
作为最后手段,您还可以卸载软件包管理器安装的版本,并按照我们的手动安装说明操作。为此,删除发行版的软件包,并用一行
sudo apt-get remove -y youtube-dl
之后,只需按照我们的手动安装说明操作:
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 hash -r
同样,从那时起,您将能够使用sudo youtube-dl -U
进行更新。
youtube-dl在Windows上启动速度极慢
在Windows Defender设置中添加youtube-dl.exe
的文件排除。
I’m getting an error Unable to extract OpenGraph title
on YouTube playlists
YouTube在2014年3月及以后更改了播放列表格式,因此您至少需要youtube-dl 2014.07.25才能下载所有YouTube视频。
如果您已使用软件包管理器、pip、setup.py或tarball安装了youtube-dl,请使用它进行更新。请注意,Ubuntu软件包似乎不再更新。由于我们与Ubuntu无关,我们无能为力。请随时向Ubuntu包装人员报告错误-他们所要做的就是将软件包更新到较新的版本。请参阅上文了解更新方式。
我在尝试使用输出模板时收到一个错误:error: using output template conflicts with using title, video ID or auto number
确保您没有将-o
与命令行或配置文件中设置的任何选项-t
、--title
、--id
、-A
或--auto-number
。移除后者(如果有的话)。
我总是必须通过-citw
吗?
默认情况下,youtube-dl打算拥有最佳选项(顺便说一句,如果您有一个令人信服的案例,认为这些选项应该有所不同,请在解释的情况下提交问题)。因此,从网页上复制长选项字符串是不必要的,有时也是有害的。特别是,-citw
中唯一经常有用的选项是-i
。
你能把-b
选项放回去吗?
大多数提出这个问题的人不知道youtube-dl现在默认下载YouTube报告的最高可用质量,在某些情况下是1080p或720p,因此您不再需要-b
选项。对于某些特定视频,也许YouTube不会报告它们以您感兴趣的特定高质量格式提供。在这种情况下,只需使用-f
选项请求它,youtube-dl将尝试下载它。
我在尝试下载视频时收到HTTP错误402。这是什么?
显然,如果您下载太多,YouTube要求您通过验证码测试。我们正在考虑提供一种方法来帮助您解决验证码,但目前,您的最佳方案是将网页浏览器指向youtube URL,解决验证码,并重新启动youtube-dl。
我需要其他程序吗?
youtube-dl在大多数网站上独立工作正常。但是,如果您想转换视频/音频,您需要avconv或ffmpeg。在某些网站上,最值得注意的是YouTube,视频可以在没有声音的情况下以更高质量的格式检索。youtube-dl将检测是否存在avconv/ffmpeg,并自动选择最佳选项。
只有安装rtmpdump时,才能下载通过RTMP协议流式传输的视频或视频格式。下载彩信和RTSP视频需要安装mplayer或mpv。
我已经下载了一个视频,但我如何播放它?
视频完全下载后,请使用任何视频播放器,如mpv、vlc或mplayer。
我用-g
提取了一个视频URL,但它不会在另一台机器/我的网页浏览器中播放。
这在很大程度上取决于服务。在许多情况下,对视频的请求(下载/播放它)必须来自相同的IP地址和相同的cookie和/或HTTP标头。使用--cookies
选项将所需的cookie写入文件中,并建议您的下载器从该文件中读取cookie。一些网站还需要使用通用用户代理,使用--dump-user-agent
查看youtube-dl使用的代理。您还可以从使用--dump-json
获得的JSON输出中获取必要的cookie和HTTP头。
使用IPv6可能是有益的;在某些情况下,限制仅适用于IPv4。一些服务(有时仅适用于视频的子集)不会通过IP地址、cookie或用户代理限制视频URL,但这些是例外,而不是规则。
请记住,包括RTMP在内的浏览器开箱即用浏览器不支持某些URL协议。如果您正在使用-g
,您自己的下载器也必须支持这些。
如果您想在不运行youtube-dl的机器上播放视频,您可以从运行youtube-dl的机器中转播视频内容。您可以使用-o -
让youtube-dl将视频流式传输到stdout,或者简单地允许播放器依次下载youtube-dl编写的文件。
错误:在视频信息中找不到fmt_url_map或conn信息
YouTube已于2011年7月切换到新的视频信息格式,旧版本的youtube-dl不支持该格式。有关如何更新youtube-dl,请参阅上文。
错误:无法下载视频
自2012年9月以来,YouTube需要额外的签名,而旧版本的youtube-dl不支持。有关如何更新youtube-dl,请参阅上文。
视频URL包含一个安培数,我正在得到一些奇怪的输出[1] 2839
或'v' is not recognized as an internal or external command
这实际上是你外壳的输出。由于ampersand是特殊的shell字符之一,因此shell会对其进行解释,阻止您将整个URL传递给youtube-dl。要禁用shell解释安培数(或任何其他特殊字符),您必须将整个URL放在引号中或使用反斜杠转义它们(哪种方法将根据您的shell起作用)。
例如,如果您的URL是https://www.youtube.com/watch?t=4&v=BaW_jenozKc 您最终应该使用以下命令:
youtube-dl 'https://www.youtube.com/watch?t=4&v=BaW_jenozKc'
奥勒冈州
youtube-dl https://www.youtube.com/watch?t=4\&v=BaW_jenozKc
对于Windows,您必须使用双引号:
youtube-dl "https://www.youtube.com/watch?t=4&v=BaW_jenozKc"
ExtractorError:找不到JS函数u’OF’
2015年2月,新的YouTube播放器在字符串中包含一个字符序列,该字符串被旧版本的youtube-dl误解。有关如何更新youtube-dl,请参阅上文。
HTTP错误429:请求太多或402:需要付款
These two error codes indicate that the service is blocking your IP address because of overuse. Usually this is a soft block meaning that you can gain access again after solving CAPTCHA. Just open a browser and solve a CAPTCHA the service suggests you and after that pass cookies to youtube-dl. Note that if your machine has multiple external IPs then you should also pass exactly the same IP you’ve used for solving CAPTCHA with --source-address
. Also you may need to pass a User-Agent
HTTP header of your browser with --user-agent
.
如果不是这样(没有建议通过服务解决验证码),那么您可以联系服务并要求他们取消阻止您的IP地址,或者——如果您已经获得了白名单的IP地址——使用--proxy
或--source-address
选项来选择另一个IP地址。
语法错误:非ASCII字符
错误
File "youtube-dl", line 2 SyntaxError: Non-ASCII character '\x93' ...
意味着您使用的是过时的Python版本。请更新到Python 2.6或2.7。
这个二进制文件是什么?代码去哪了?
自2012年6月(#342)以来,youtube-dl被打包为可执行的zip文件,只需解压缩(可能需要先在某些系统上重命名为youtube-dl.zip
)或克隆git存储库,如上所述。如果您修改代码,您可以通过执行__main__.py
文件来运行它。要重新编译可执行文件,请运行make youtube-dl
。
前任因丢失而抛出错误MSVCR100.dll
要运行exe,您需要首先安装Microsoft Visual C++ 2010 Service Pack 1 Redistributable Package(x86)。
在Windows上,我应该如何设置ffmpeg和youtube-dl?我应该把exe文件放在哪里?
如果您将youtube-dl和ffmpeg放在运行命令的同一目录中,它会起作用,但这相当麻烦。
要使不同的目录工作-无论是为ffmpeg,还是youtube-dl,还是两者兼而有之-只需创建目录(例如,C:\bin
,或C:\Users\<User name>\bin
),将所有可执行文件直接放在那里,然后将PATH环境变量设置为包含该目录。
从那时起,重新启动shell后,无论您位于哪个目录,您都可以通过键入youtube-dl
或ffmpeg
来访问youtube-dl和ffmpeg(youtube-dl将能够找到ffmpeg)。
如何将下载放入特定的文件夹?
使用-o
指定输出模板,例如-o "/home/user/videos/%(title)s-%(id)s.%(ext)s"
如果您希望所有下载都使用这个,请将该选项放入您的配置文件中。
如何下载以-
开头的视频?
要么先于https://www.youtube.com/watch?v=
或将ID与选项分开--
:
youtube-dl -- -wNyEUrxzFU youtube-dl "https://www.youtube.com/watch?v=-wNyEUrxzFU"
如何将cookie传递到youtube-dl?
使用--cookies
选项,例如--cookies /path/to/cookies/file.txt
。
为了从浏览器中提取cookie,请使用任何符合要求的浏览器扩展来导出cookie。例如,获取cookies.txt(适用于Chrome)或cookies.txt(适用于Firefox)。
Note that the cookies file must be in Mozilla/Netscape format and the first line of the cookies file must be either # HTTP Cookie File
or # Netscape HTTP Cookie File
. Make sure you have correct newline format in the cookies file and convert newlines if necessary to correspond with your OS, namely CRLF
(\r\n
) for Windows and LF
(\n
) for Unix and Unix-like systems (Linux, macOS, etc.). HTTP Error 400: Bad Request
when using --cookies
is a good sign of invalid newline format.
当特定提取器没有显式实现登录时,将cookie传递到youtube-dl是解决登录的好方法。另一个用例是绕过验证码,一些网站要求您在特定情况下解决才能访问(例如YouTube,CloudFlare)。
如何直接流式传输到媒体播放器?
您首先需要告诉youtube-dl使用-o -
将媒体流式传输到stdout,还需要告诉您的媒体播放器从stdin阅读(它必须能够进行流媒体),然后将前者连接到后者。例如,流式传输到vlc可以通过以下方式实现:
youtube-dl -o - "https://www.youtube.com/watch?v=BaW_jenozKcj" | vlc -
我如何只从播放列表中下载新视频?
使用下载存档功能。使用此功能,您最初应该使用--download-archive /path/to/download/archive/file.txt
下载完整的播放列表,该播放列表将记录特殊文件中所有视频的标识符。每次使用相同的--download-archive
进行后续运行,将仅下载新视频,并跳过之前下载过的所有视频。请注意,文件中仅记录成功的下载。
例如,一开始,
youtube-dl --download-archive archive.txt "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re"
将下载完整的PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re
播放列表并创建一个文件archive.txt
。每次后续运行只会下载新视频(如果有的话):
youtube-dl --download-archive archive.txt "https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re"
我应该将--hls-prefer-native
添加到我的配置中吗?
当youtube-dl检测到HLS视频时,它可以使用内置下载器或ffmpeg下载。由于许多HLS流略有无效,ffmpeg/youtube-dl每个流都比另一个更好地处理一些无效案例,因此如果需要,可以选择切换下载器。
当youtube-dl知道一个特定的下载器对给定的网站效果更好时,将选择该下载器。否则,youtube-dl将选择最佳的下载器进行一般兼容性,目前恰好是ffmpeg。随着内置下载器和/或ffmpeg的改进,此选择可能会在未来版本的youtube-dl中发生变化。
特别是,通用提取器(当您的网站不在youtube-dl支持的网站列表中时使用)不能强制指定一个特定的下载器。
如果您将--hls-prefer-native
或--hls-prefer-ffmpeg
放入配置中,则不同的视频子集将无法正确下载。相反,最好提交问题或拉取请求,详细说明了为什么本机或ffmpeg HLS下载器是您用例的更好选择。
你能添加对这个动漫视频网站或免费显示当前电影的网站的支持吗?
作为政策(以及合法性),youtube-dl不包括对专门侵犯版权的服务的支持。根据经验,如果您无法轻松找到该服务显然允许分发的视频(即由创作者、创作者的分销商上传或根据免费许可证发布的视频),该服务可能不适合包含在youtube-dl。
关于该服务的注释,即他们不托管侵权内容,而只是链接到那些托管侵权内容的人,这证明该服务不应包含在youtube-dl中。当服务的整个首页都装满了他们不允许分发的视频时,任何DMCA注释也是如此。如果服务未经授权完整显示受版权保护的视频,则“合理使用”注释同样不令人信服。
不过,对确实购买其内容分发权的服务的支持请求是完全可以的。如有疑问,您可以简单地包含一个提及合法购买内容的来源。
我怎样才能加快解决我问题的工作?
(也称为:帮助,我的重要问题没有解决!)youtube-dl核心开发人员团队规模相当小。虽然我们尽最大努力解决尽可能多的问题,但有时这可能需要相当长的时间。为了加快您的问题,您可以做到以下几点:
首先,请在我们的问题跟踪器上报告问题。这使我们能够协调用户和开发人员的所有努力,并作为一个统一点。不幸的是,youtube-dl项目已经变得太大了,无法使用个人电子邮件作为有效的沟通渠道。
请阅读下面的错误报告说明。许多错误缺乏所有必要的信息。如果可以,请为youtube-dl开发人员提供代理、VPN或shell访问。如果可以,请在多个国家或地区的多台电脑上测试问题,以排除本地审查或配置错误问题。
如果没有人有兴趣解决您的问题,欢迎您自行处理并提交拉取请求(或强迫/支付其他人这样做)。
请随时通过写一篇小评论来解决这个问题(“问题仍然存在于youtube-dl版本中……来自法国,但来自比利时),但请每月不超过一次。请不要将您的问题声明为important
或urgent
。
如何检测youtube-dl是否支持给定的URL?
首先,请查看受支持网站的列表。请注意,网站有时会更改其URL方案(例如,从https://example.com/video/1234567到https://example.com/v/1234567),youtube-dl报告该列表中服务的URL不受支持。在这种情况下,只需报告一个错误。
无法检测到是否支持URL。这是因为youtube-dl包含一个匹配所有URL的通用提取器。您可能会试图禁用、排除或删除通用提取器,但通用提取器不仅允许用户从许多从其他服务嵌入视频的网站上提取视频,还可用于从其自己托管的服务中提取视频。因此,我们既不建议也不支持禁用、排除或删除通用提取器。
如果您想了解是否支持给定的URL,只需使用它调用youtube-dl即可。如果您没有收到任何视频,URL可能不引用视频或不受支持。您可以通过检查输出(如果您在控制台上运行youtube-dl)或从Python程序运行时捕获UnsupportedError
异常来找出哪个。
为什么我在提交错误时需要经历这么多繁文缛节?
在我们有问题模板之前,尽管我们提供了广泛的错误报告说明,但我们收到的大约80%的问题报告毫无用处,例如,由于人们使用了数百个旧版本的古代版本,因为简单的语法错误(不是在youtube-dl中,而是一般的shell使用),因为这个问题以前已经多次报告过,因为人们实际上没有阅读错误消息,即使上面写着“请安装ffmpeg”,因为人们没有提到他们试图下载的URL和许多更简单、容易避免的问题,其中许多问题与youtube-dl完全无关。
youtube-dl是一个由太少的志愿者组成的开源项目,所以我们宁愿花时间修复错误,在那里我们确定这些简单的问题都不适用,并且我们可以有信心在不反复询问记者的情况下重现问题。因此,youtube-dl -v YOUR_URL_HERE
的输出实际上是提交问题所需的全部。问题模板还指导您完成一些可以完成的基本步骤,例如检查您的youtube-dl版本是否是最新的。
开发人员说明
大多数用户不需要构建youtube-dl,可以下载构建版本或从其发行版中获取它们。
要作为开发人员运行youtube-dl,您也不需要构建任何东西。只需执行
python -m youtube_dl
要运行测试,只需调用您最喜欢的测试运行器,或直接执行测试文件;以下任何工作:
python -m unittest discover python test/test_download.py nosetests
有关如何运行提取器特定测试用例,请参阅新提取器教程的第6项。
如果您想自己创建youtube-dl的构建,您需要
- Python
- 制作(仅支持GNU制作)
- 潘多克
- 压缩包
- 鼻孔测试
添加对新网站的支持
如果您想添加对新网站的支持,首先请确保本网站不专门用于版权侵权。youtube-dl不支持此类网站,因此添加支持它们的拉取请求将被拒绝。
在您确保本网站合法分发其内容后,您可以遵循此快速列表(假设您的服务称为yourextractor
):
- 叉此存储库
- 查看源代码:
git clone git@github.com:YOUR_GITHUB_USERNAME/youtube-dl.git
- 启动一个新的git分支
cd youtube-dl git checkout -b yourextractor
- 从这个简单的模板开始,并将其保存到
youtube_dl/extractor/yourextractor.py
:# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class YourExtractorIE(InfoExtractor): _VALID_URL = r’https?://(?:www\.)?yourextractor\.com/watch/(?P<id>[0-9]+)’ _TEST = { ‘url’: ‘https://yourextractor.com/watch/42’, ‘md5’: ‘TODO: md5 sum of the first 10241 bytes of the video file (use –test)’, ‘info_dict’: { ‘id’: ’42’, ‘ext’: ‘mp4’, ‘title’: ‘Video title goes here’, ‘thumbnail’: r’re:^https?://.*\.jpg$’, # TODO more properties, either as: # * A value # * MD5 checksum; start the string with md5: # * A regular expression; start the string with re: # * Any Python type (for example int or float) } } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) # TODO more code goes here, for example … title = self._html_search_regex(r'<h1>(.+?)</h1>’, webpage, ‘title’) return { ‘id’: video_id, ‘title’: title, ‘description’: self._og_search_description(webpage), ‘uploader’: self._search_regex(r'<div[^>]+id=”uploader”[^>]*>([^<]+)<‘, webpage, ‘uploader’, fatal=False), # TODO more properties (see youtube_dl/extractor/common.py) } - 在
youtube_dl/extractor/extractors.py
中添加导入。 - 运行
python test/test_download.py TestDownload.test_YourExtractor
。这一开始应该会失败,但你可以不断重新运行它,直到完成。如果您决定添加多个测试(实际上是测试用例),请将_TEST
重命名为_TESTS
,并将其制作成词典列表。然后,这些测试将命名为TestDownload.test_YourExtractor
、TestDownload.test_YourExtractor_1
、TestDownload.test_YourExtractor_2
等。笔记:- 测试名称使用提取器类名,而无需跟踪
IE
- tests with
only_matching
key in test’s dict are not counted.
- 测试名称使用提取器类名,而无需跟踪
- 查看
youtube_dl/extractor/common.py
,了解可能的辅助方法,并详细说明您的提取器应该和可能返回什么。添加任意数量的测试和代码。 - 确保您的代码遵循youtube-dl编码约定,并使用flake8检查代码:
$ flake8 youtube_dl/extractor/yourextractor.py
- 确保您的代码在youtube-dl声称支持的所有Python版本下工作,即2.6、2.7和3.2+。
- 测试通过后,添加新文件并提交它们并推送结果,如下所示:
$ git add youtube_dl/extractor/extractors.py $ git add youtube_dl/extractor/yourextractor.py $ git commit -m '[yourextractor] Add new extractor' $ git push origin yourextractor
- 最后,创建一个拉取请求。然后,我们将对其进行审核并合并。
无论如何,非常感谢您的贡献!
youtube-dl编码约定
本节介绍了编写惯用、健壮和面向未来的提取器代码的指南。
提取器本质上非常脆弱,因为它们依赖于第三方媒体主机提供的源数据的布局,并且这种布局往往会发生变化。作为提取器实现者,您的任务不仅是编写可以正确提取媒体链接和元数据的代码,而且要尽量减少对源布局的依赖,甚至使代码预见未来的潜在更改,并为此做好准备。这很重要,因为它将允许提取器不会中断小的布局更改,从而保持旧的youtube-dl版本正常工作。尽管通过发射带有修复程序的新版本的youtube-dl很容易解决这个破损问题,但所有以前的版本都在所有存储库和发行版的软件包中都坏了,这些软件包可能无法及时地从我们这里获取更新。不用说,一些非滚动发行版可能永远不会收到更新。
强制性和可选的元字段
为了使提取工作,youtube-dl依赖于提取器提取的元数据,并提供通过信息词典或简单信息指令表达的youtube-dl。只有信息指令中的以下元字段被认为是youtube-dl成功提取过程的必填项:
id
(媒体标识符)title
(媒体标题)url
(媒体下载 URL)或formats
事实上,只有最后一个选项在技术上是强制性的(即,如果您无法确定媒体的下载位置,则提取没有任何意义)。但根据惯例,youtube-dl也将id
和title
视为强制性的。因此,上述元字段是没有提取就没有任何意义的关键数据,如果其中任何一个无法提取,则提取器将被视为完全损坏。
除上述字段外,任何字段都被视为可选字段。这意味着提取应该容忍这些字段的来源可能不可用(即使它们目前总是可用)和面向未来的情况,以免中断通用强制字段的提取。
示例:
假设您有一些源字典meta
,您通过HTTP请求作为JSON获取,它有一个关键summary
:
meta = self._download_json(url, video_id)
假设此时meta
的布局是:
{ ... "summary": "some fancy summary text", ... }
假设您想提取summary
并将其作为description
放入生成的信息指令中。由于description
是一个可选的元字段,您应该准备好meta
命令中可能缺少此密钥,因此您应该像以下一样提取它:
description = meta.get('summary') # correct
不喜欢:
description = meta['summary'] # incorrect
如果summary
在稍后从meta
中消失,后者将中断KeyError
的提取过程,但使用前一种方法,提取将继续将description
设置为None
,这完全没问题(请记住,None
相当于没有数据)。
同样,当使用_search_regex
、_html_search_regex
或类似方法从网页中提取可选数据时,您应该传递fatal=False
,例如:
description = self._search_regex( r'<span[^>]+id="title"[^>]*>([^<]+)<', webpage, 'description', fatal=False)
如果_search_regex
无法提取description
,则将fatal
设置为False
,它将发出警告并继续提取。
您还可以传递default=<some fallback value>
,例如:
description = self._search_regex( r'<span[^>]+id="title"[^>]*>([^<]+)<', webpage, 'description', default=None)
失败时,此代码将静默地继续提取,并将description
设置为None
。这对于可能存在也可能不存在的元字段非常有用。
提供回退
在提取元数据时,请尝试从多个来源提取元数据。例如,如果title
存在于几个地方,请尝试至少从其中一些地方提取。这使它更适合未来,以防一些来源不可用。
示例:
假设上一个示例中的meta
有一个title
,你即将提取它。由于title
是一个强制性的元字段,因此您应该最终获得以下内容:
title = meta['title']
如果title
将来因主机方面的一些更改而从meta
中删除,则提取将失败,因为title
是强制性的。这是意料之中的。
Assume that you have some another source you can extract title
from, for example og:title
HTML meta of a webpage
. In this case you can provide a fallback scenario:
title = meta.get('title') or self._og_search_title(webpage)
此代码将尝试首先从meta
中提取,如果失败,它将尝试从webpage
中提取og:title
。
正则表达式
不要捕获您不使用的组
捕获组必须表明它在代码的某个地方使用过。任何未使用的组都必须是非捕获的。
示例:
不要在这里捕获id属性名称,因为无论如何您都无法将其用于任何用途。
正确:
r'(?:id|ID)=(?P<id>\d+)'
错误:
r'(id|ID)=(?P<id>\d+)'
使正则表达轻松灵活
使用正则表达式时,请尝试将其写成模糊、放松和灵活,跳过更有可能更改的微不足道的部分,允许引用值的单引号和双引号等。
示例:
假设您需要从以下HTML代码中提取title
:
<span style="position: absolute; left: 910px; width: 90px; float: right; z-index: 9999;" class="title">some fancy title</span>
该任务的代码应该类似于:
title = self._search_regex( r'<span[^>]+class="title"[^>]*>([^<]+)', webpage, 'title')
或者更好的是:
title = self._search_regex( r'<span[^>]+class=(["\'])title\1[^>]*>(?P<title>[^<]+)', webpage, 'title', group='title')
注意如何容忍style
属性值的潜在变化,或从使用双引号切换到单class
属性:
代码绝对不应该看起来像:
title = self._search_regex( r'<span style="position: absolute; left: 910px; width: 90px; float: right; z-index: 9999;" class="title">(.*?)</span>', webpage, 'title', group='title')
长线政策
有一个软限制,可以将代码行保持在80个字符以下。这意味着,如果可能的话,如果它不能使可读性和代码维护恶化,则应该尊重它。
例如,您绝不应将URL等长字符串文字或其他经常复制的实体拆分为多行,以适应此限制:
正确:
'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4'
错误:
'https://www.youtube.com/watch?v=FqZTN594JQw&list=' 'PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4'
内联值
提取变量对于减少代码重复和提高复杂表达式的可读性是可以接受的。但是,您应该避免提取仅使用一次的变量,并将它们移动到提取器文件的相反部分,这使得读取线性流变得困难。
示例:
正确:
title = self._html_search_regex(r'<title>([^<]+)</title>', webpage, 'title')
错误:
TITLE_RE = r'<title>([^<]+)</title>' # ...some lines of code... title = self._html_search_regex(TITLE_RE, webpage, 'title')
崩溃后备
多个回退值可能会很快变得笨拙。通过模式列表将多个回退值折叠到单个表达式中。
示例:
很好:
description = self._html_search_meta( ['og:description', 'description', 'twitter:description'], webpage, 'description', default=None)
Unwieldy:
description = ( self._og_search_description(webpage, default=None) or self._html_search_meta('description', webpage, default=None) or self._html_search_meta('twitter:description', webpage, default=None))
支持模式列表的方法是:_search_regex
、_html_search_regex
、_og_search_property
、_html_search_meta
。
尾随括号
始终在最后一个参数之后移动后面的括号。
示例:
正确:
lambda x: x['ResultSet']['Result'][0]['VideoUrlSet']['VideoUrl'], list)
错误:
lambda x: x['ResultSet']['Result'][0]['VideoUrlSet']['VideoUrl'], list, )
使用方便的转换和解析功能
将所有提取的数字数据从youtube_dl/utils.py
:int_or_none
,float_or_none
的安全函数中。也将它们用于字符串到数字转换。
使用url_or_none
进行安全的URL处理。
使用try_get
从解析的JSON中安全地提取元数据。
使用unified_strdate
进行uniform upload_date
或任何YYYYMMDD
元字段提取,unified_timestamp
用于统一timestamp
提取,parse_filesize
用于filesize
提取,parse_count
用于计数元字段提取,parse_resolution
,parse_duration
用于duration
提取,parse_age_limit
用于age_limit
提取。
探索youtube_dl/utils.py
以获取更有用的便利功能。
更多示例
安全从解析的JSON中提取可选描述
description = try_get(response, lambda x: x['result']['video'][0]['summary'], compat_str)
安全提取更多可选元数据
video = try_get(response, lambda x: x['result']['video'][0], dict) or {} description = video.get('summary') duration = float_or_none(video.get('durationMs'), scale=1000) view_count = int_or_none(video.get('views'))
嵌入YOUTUBE-DL
youtube-dl尽最大努力成为一个好的命令行程序,因此应该可以从任何编程语言调用。如果您在解析其输出时遇到任何问题,请随时创建报告。
从Python程序中,您可以以更强大的方式嵌入youtube-dl,如下所示:
from __future__ import unicode_literals import youtube_dl ydl_opts = {} with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
最有可能的是,您会想要使用各种选项。有关可用选项的列表,请查看youtube_dl/YoutubeDL.py
。首先,如果您想拦截youtube-dl的输出,请设置一个logger
对象。
以下是一个更完整的程序示例,该程序仅输出错误(下载完成后显示一条短信),并将视频下载/转换为mp3文件:
from __future__ import unicode_literals import youtube_dl class MyLogger(object): def debug(self, msg): pass def warning(self, msg): pass def error(self, msg): print(msg) def my_hook(d): if d['status'] == 'finished': print('Done downloading, now converting ...') ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'logger': MyLogger(), 'progress_hooks': [my_hook], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
漏洞
错误和建议应在以下网址报告:https://github.com/ytdl-org/youtube-dl/issues。除非您被提示或有其他相关原因(例如GitHub未能接受错误报告),请不要通过电子邮件发送错误报告。如需讨论,请加入我们freenode(网络聊天)上的IRC频道#youtube-dl。
使用-v
运行时,请包含youtube-dl的完整输出,即在命令行中添加-v
标志,复制整个输出并将其发布在“`”包装的问题正文中,以便更好地格式化。它应该看起来与此相似:
$ youtube-dl -v <your command line> [debug] System config: [] [debug] User config: [] [debug] Command-line args: [u'-v', u'https://www.youtube.com/watch?v=BaW_jenozKcj'] [debug] Encodings: locale cp1251, fs mbcs, out cp866, pref cp1251 [debug] youtube-dl version 2015.12.06 [debug] Git HEAD: 135392e [debug] Python version 2.6.6 - Windows-2003Server-5.2.3790-SP2 [debug] exe versions: ffmpeg N-75573-g1d0487f, ffprobe N-75573-g1d0487f, rtmpdump 2.4 [debug] Proxy map: {} ...
不要发布详细日志的屏幕截图;只有纯文本是可以接受的。
输出(包括第一行)包含重要的调试信息。没有完整输出的问题通常无法重现,因此即使有,也无法在短时间内解决。
请再次重读您的问题,以避免出现一些常见错误(您可以也应该将此作为清单):
对问题本身的描述是否足够?
我们经常收到我们无法真正破译的问题报告。虽然在大多数情况下,我们最终在多次询问后获得了所需的信息,但这对我们的资源造成了不必要的消耗。许多贡献者,包括我,也不是母语者,所以我们可能会误读一些部分。
因此,请详细说明您请求的功能,或者您希望修复哪些错误。确保它很明显
- 问题是什么
- 如何修复它
- 您提议的解决方案会是什么样子
如果您的报告短于两行,它几乎可以肯定遗漏了其中一些,这使得我们很难对此做出回应。我们通常过于礼貌,无法直接解决问题,但缺少的信息可能会造成误解。作为一名承诺者,我经常对这些问题感到沮丧,因为我推进这些问题的唯一可能方法是一遍又一遍地要求澄清。
对于错误报告,这意味着当使用-v
标志调用时,您的报告应包含youtube-dl的完整输出。您收到的(大多数)错误消息甚至是这样说的,但您不会相信我们的错误报告中有多少不包含此信息。
如果您的服务器有多个IP,或者您怀疑存在审查,添加--call-home
可能是获得更多诊断的好主意。如果错误是ERROR: Unable to extract ...
并且您无法从多个国家重现它,请添加--dump-pages
(警告:这将产生相当大的输出,通过将>log.txt 2>&1
添加到命令行将其重定向到文件log.txt
),或上传您在某个地方添加--write-pages
时获得的.dump
文件。
站点支持请求必须包含示例 URL。示例URL是您可能想要下载的URL,例如https://www.youtube.com/watch?v=BaW_jenozKc
。应该有一个明显的视频。除非常特殊的情况外,视频服务的主页(例如https://www.youtube.com/
)不是示例URL。
你在使用最新版本吗?
在报告任何问题之前,请键入youtube-dl -U
。这应该会报告您是最新的。我们收到的大约20%的报告已经修复,但人们正在使用过时的版本。功能请求也适用于此项。
问题是否已经记录在案?
确保有人还没有打开您尝试打开的问题。在窗口顶部搜索或浏览此存储库的GitHub问题。如果有问题,请随时写一些大意为“这也会影响我,版本为2015.01.01。以下是有关该问题的更多信息:……”。虽然有些问题可能很旧,但其中的新帖子通常会刺激快速活动。
为什么现有选项不够?
在请求新功能之前,请快速查看支持的选项列表。许多功能请求都是针对实际上已经存在的功能!请绝对在问题报告中展示您的工作,并详细说明现有的类似选项如何解决您的问题。
您的错误报告中有足够的上下文吗?
人们想解决问题,并且通常认为他们帮了我们一个忙,将他们更大的问题(例如,想跳过已经下载的文件)分解为特定请求(例如,要求我们在下载信息页面之前查看文件是否存在)。然而,经常发生的是,他们将问题分为两个步骤:一个简单,一个不可能(或极其复杂)。
然后,当原始问题可以更容易地解决时,我们会收到一个非常复杂的请求,例如将下载的视频ID记录在单独的文件中。为了避免这种情况,您必须在不明显的情况下包含更大的上下文。特别是,每个不包含添加对新站点支持的功能请求都应包含一个用例场景,解释在什么情况下缺失的功能会有用。
问题是否涉及一个问题,而只涉及一个问题?
我们的一些用户似乎认为他们可以或应该打开的问题是有限的。他们能够或应该打开的问题没有限制。虽然能够将您的所有问题转储到一张票据中似乎很有吸引力,但这意味着解决您其中一个问题的人不能将问题标记为已关闭。通常,报告一堆问题会导致票务挥之不去,因为没有人想攻击那个庞然大物,直到有人仁慈地将问题分成多个问题。
特别是,每个站点支持请求问题都应仅涉及一个站点的服务(通常在公共域下,但始终使用相同的后端技术)。在同一问题上,请勿请求支持vimeo用户视频、白宫播客和Google Plus页面。此外,请确保您不会在功能请求旁边发布错误报告。根据经验,功能请求不包括与手头功能无关的youtube-dl输出。不要在请求新的视频服务时发布网络错误的报告。
有人需要这个功能吗?
仅发布您(或您可以亲自交谈的无行为能力的朋友)所需的功能。不要发布功能,因为它们看起来是个好主意。如果它们真的有用,它们将被需要它们的人要求。
你的问题是关于youtube-dl吗?
这听起来可能很奇怪,但我们收到的一些错误报告与youtube-dl完全无关,并且与不同的应用程序甚至记者自己的应用程序有关。请确保您实际上使用的是youtube-dl。如果您正在为youtube-dl使用UI,请向提供UI的实际应用程序的维护者报告该错误。另一方面,如果您的youtube-dl用户界面以某种方式失败,您认为与youtube-dl有关,请务必继续报告该错误。
版权
youtube-dl由版权所有者发布到公共领域。
这个README文件最初由Daniel Bolton编写,同样发布到公共领域。