youtube-dl

repository·master·Indexed Aug 11, 2026

https://github.com/ytdl-org/youtube-dl

A platform-agnostic command-line program designed to download videos from YouTube and various other video hosting platforms. Requires a Python interpreter. Features include metadata filtering via --match-filter, support for external downloaders like ffmpeg and aria2c, playlist management, and extensive options for video formats, subtitles, and authentication.

Tokens
15K
Snippets
41
Records
53
Agent score
70%

What's inside youtube-dl

  1. Use youtube-dl as a command-line tool or Python library

    master

    youtube-dl is a versatile tool designed for downloading videos from YouTube.com and various other websites. It can be used in two primary ways:

    1. Command-line interface (CLI): Run it directly from your terminal to download videos.
    2. Python library: Import it into your Python scripts to integrate video downloading capabilities into your own applications.
  2. Safely extract nested data from JSON using traverse_obj

    master

    When writing custom extractors, use traverse_obj to safely navigate complex, nested JSON structures. This prevents crashes if keys are missing or the structure changes.

    traverse_obj allows you to specify a path and a transformation function (like txt_or_none, int_or_none, or url_or_none) to apply to the extracted value. You can use Ellipsis (...) to iterate over lists within the path.

    # Example of traversing a nested 'media' list to extract specific fields
    for fmt in traverse_obj(media_json, ('media', Ellipsis, {
            'format_id': ('type', T(txt_or_none)),
            'url': ('url', T(url_or_none)),
            'width': ('size', T(int_or_none)), 
        })):
        # fmt is now a dictionary containing the extracted and transformed keys
        if 'url' not in fmt:
            continue
        # ... process fmt
  3. Collapse fallback values using lists of patterns

    master

    When implementing extractors, avoid unwieldy or chains for fallback values. Instead, pass a list of patterns to methods that support them. This allows you to attempt multiple metadata lookups in a single expression.

    Supported methods include:

    • _search_regex
    • _html_search_regex
    • _og_search_property
    • _html_search_meta
    description = self._html_search_meta(
        ['og:description', 'description', 'twitter:description'],
        webpage, 'description', default=None)
  4. Coding conventions for extractors

    master

    When writing extractors, follow these principles to ensure robustness:

    Mandatory vs Optional Metafields

    • Mandatory: id, title, and url (or formats). If these fail, the extraction is considered broken.
    • Optional: Any other field. Extraction should be tolerant of missing optional fields.

    Robust Extraction Patterns

    • Use .get() for optional data: Instead of meta['summary'], use meta.get('summary') to avoid KeyError if the key is missing.
    • Use fatal=False: When using _search_regex or _html_search_regex for optional fields, set fatal=False so the extractor continues even if the regex fails.
    • Provide Fallbacks: Try to extract mandatory fields from multiple sources (e.g., meta.get('title') or self._og_search_title(webpage)).

    Regular Expressions

    • Non-capturing groups: Use (?:...) for groups that are not used in the code to avoid unnecessary overhead.
    • Be flexible: Write "fuzzy" regexes that skip insignificant parts (like specific CSS styles) to tolerate minor layout changes.

    Code Style

    • Line Length: Respect a soft limit of 80 characters, but never split long string literals like URLs across multiple lines.
    # Correct: Tolerant extraction of optional field
    description = meta.get('summary')
    
    # Correct: Using fallback for mandatory field
    title = meta.get('title') or self._og_search_title(webpage)
    
    # Correct: Flexible regex
    title = self._search_regex(r'<span[^>]+class=(["\'])title\1[^>]*>([^<]+)', webpage, 'title')
  5. Filter formats using metadata conditions

    master

    You can refine format selection by adding conditions in brackets [] to the -f flag.

    Numeric Meta Fields (supports <, <=, >, >=, =, !=):

    • filesize: Number of bytes.
    • width: Video width.
    • height: Video height.
    • tbr: Average bitrate (KBit/s).
    • abr: Average audio bitrate (KBit/s).
    • vbr: Average video bitrate (KBit/s).
    • asr: Audio sampling rate (Hertz).
    • fps: Frame rate.

    String Meta Fields (supports =, ^= (starts with), $= (ends with), *= (contains)):

    • ext: File extension.
    • acodec: Audio codec.
    • vcodec: Video codec.
    • container: Container format.
    • protocol: Download protocol (e.g., http, https, m3u8).
    • format_id: Format description.
    • language: Language code.

    Advanced Filtering Rules:

    • Negation: Prefix any comparison with ! to negate it (e.g., !*= means 'does not contain').
    • Handling Unknown Values: If a metadata field is unknown, the filter will exclude the format unless you append a ? to the operator (e.g., [height <=? 720] includes videos where height is unknown or $\le$ 720).
    • Grouping: Use parentheses to group selectors (e.g., -f '(mp4,webm)[height<480]').
    youtube-dl -f "best[height=720]"
    youtube-dl -f "[filesize>10M]"
    youtube-dl -f "[height <=? 720][tbr>500]"
  6. Install youtube-dl on UNIX (Linux, macOS, etc.)

    master

    You can install youtube-dl using curl or wget by downloading the latest version to /usr/local/bin/ and setting the appropriate permissions.

    Using curl:

    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

    Using 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
    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
  7. Embed youtube-dl in a Python program

    master

    You can use youtube_dl as a library within your Python applications. The primary interface is the youtube_dl.YoutubeDL class, which should be used as a context manager. You pass a configuration dictionary (ydl_opts) to the constructor to control behavior such as format selection, post-processors, logging, and progress hooks.

    from __future__ import unicode_literals
    import youtube_dl
    
    # Basic usage
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])
  8. Download only new videos from a playlist

    master

    Use the --download-archive feature to keep track of downloaded videos. By providing a text file to this option, youtube-dl will record the identifiers of successfully downloaded videos and skip them in subsequent runs.

    # Initial run to populate the archive
    youtube-dl --download-archive archive.txt "https://www.youtube.com/playlist?list=ID"
    
    # Subsequent runs will only download new videos
    youtube-dl --download-archive archive.txt "https://www.youtube.com/playlist?list=ID"
  9. Configure youtube-dl via configuration files

    master

    Instead of typing long commands, you can save your preferred options in a configuration file. The options used in the file are identical to the command-line switches.

    Configuration File Locations

    • Linux/macOS (System-wide): /etc/youtube-dl.conf
    • Linux/macOS (User-wide): ~/.config/youtube-dl/config
    • Windows (User-wide): %APPDATA%\youtube-dl\config.txt or C:\Users\<user name>\youtube-dl.conf

    Usage Rules

    • No Whitespace: There must be no whitespace after the dash in flags (e.g., use -o, not - o).
    • Override Config: Use --ignore-config to run a command without loading the configuration file, or --config-location PATH to specify a custom config file.

    Example Configuration

    Create a file with the following content to always extract audio and save to a specific directory:

    # 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
  10. Use cookies with youtube-dl

    master

    To bypass login requirements or solve CAPTCHAs, use the --cookies option pointing to a file in Mozilla/Netscape format. The first line of the file must be # HTTP Cookie File or # Netscape HTTP Cookie File.

    You can export cookies from your browser using extensions like 'Get cookies.txt LOCALLY' (Chrome) or 'cookies.txt' (Firefox).

    youtube-dl --cookies /path/to/cookies/file.txt "URL"