pytubefix Documentation

repository·main·Indexed 23 days ago

https://github.com/juanbindez/pytubefix

A Python 3 library for downloading YouTube videos, playlists, and channels. A fork of pytube featuring support for high-resolution MP4s, audio-only extraction, subtitle handling, and an asynchronous interface via AsyncYouTube. Key capabilities include OAuth authentication for age-restricted content, search functionality with advanced filters, and access to video chapters and key moments. The library is dependency-free and supports both Progressive and DASH streams.

Tokens
17.6K
Snippets
50
Records
123
Agent score
65%

What's inside pytubefix

  1. Overview of pytubefix features

    main

    pytubefix is a lightweight, dependency-free Python library and CLI utility for downloading YouTube content. Key features include:

    • Support for both Progressive and DASH streams.
    • Callback registration for on_download_progress and on_download_complete events.
    • Built-in Command-line Interface (CLI).
    • Caption track support with output to .srt (SubRip Subtitle) format.
    • Ability to capture thumbnail URLs.
    • No third-party dependencies required.
  2. Overview of pytubefix

    main
    pytubefix is a Python library designed for downloading YouTube videos. It is a fork of the pytube library, specifically updated to provide improved stability and additional features. It is compatible with Python 3.7+ and adheres to PEP 8 style guidelines.
  3. Understand DASH vs Progressive streams

    main

    YouTube uses two main streaming techniques that affect how you download media:

    1. Progressive Streams: These contain both video and audio in a single file. They are easier to download but are typically limited to resolutions of 720p and below.
    2. DASH (Dynamic Adaptive Streaming over HTTP) / Adaptive Streams: These split the video and audio tracks into separate files. These provide the highest quality (e.g., 1080p, 4K).

    Note for high-quality downloads: If you choose DASH streams, you must download both the audio and video tracks separately and then use a tool like FFmpeg to merge them into a single file.

  4. Use the Buffer class for in-memory data handling

    main

    The Buffer class is designed for efficient handling of large data or media content (like video/audio streams) in memory. It supports various data sources including streams and strings, making it ideal for processing YouTube data, saving temporary metadata, or streaming to external applications without writing to disk first.

    Key methods:

    • download_in_buffer(stream_or_string): Downloads data into an in-memory buffer from a stream or a string.
    • redirect_to_stdout(): Redirects the buffer content to standard output (stdout).
    • read(): Reads the content from the buffer.
    • clear(): Clears the buffer for reuse.
    from pytubefix import YouTube, Buffer
    
    buffer = Buffer()
    url = "URL"
    
    yt = YouTube(url)
    ys = yt.streams.get_audio_only()
    
    buffer.download_in_buffer(ys)
    buffer.redirect_to_stdout()
  5. How AsyncYouTube works

    main

    The AsyncYouTube class provides a fully asynchronous interface for interacting with YouTube data. It is designed to prevent blocking the event loop when fetching metadata or streams.

    Key behaviors:

    • Most metadata methods (title(), views(), likes(), author(), thumbnail_url(), chapters(), key_moments()) and the streams() method must be awaited.
    • You can initialize it via a URL or using AsyncYouTube.from_id(video_id).
    • Note: While the interface is async, the stream.download() method is a synchronous/blocking call by design. To track progress, you must use register_on_progress_callback and register_on_complete_callback.
    import asyncio
    from pytubefix import AsyncYouTube
    
    URL = "YOUR_VIDEO_URL"
    
    async def main():
        yt = AsyncYouTube(URL, use_oauth=True, allow_oauth_cache=True)
        streams = await yt.streams()
        for stream in streams:
            print(stream)
    
    if __name__ == '__main__':
        asyncio.run(main())
  6. Core features of pytubefix

    main

    The library provides several key capabilities for interacting with YouTube content:

    • Downloading: Supports both video and audio streams.
    • Decryption: Handles YouTube's signature cipher decryption.
    • API Interaction: Interacts with YouTube's internal API (Innertube).
    • Content Discovery: Support for playlists, channels, and search functionality.
    • Advanced Features: Support for asynchronous operations, bot protection handling, captions, and chapters.
  7. Access search results, videos, shorts, playlists, and channels

    main

    A Search object provides several attributes to filter the types of content returned from a search query:

    • .results: A list of all returned objects (including videos, shorts, playlists, and channels).
    • .videos: A list containing only YouTube video objects.
    • .shorts: A list containing only YouTube short objects (note: shorts are instances of the same YouTube class).
    • .playlist: A list of playlist objects. Access the URL of a playlist via .playlist_url.
    • .channel: A list of Channel objects.
    • .completion_suggestions: A list of strings containing autocomplete suggestions related to the search query.
    from pytubefix import Search
    
    s = Search('YouTube Rewind')
    
    # Access different content types
    print(s.videos)
    print(s.shorts)
    print(s.playlist)
    print(s.channel)
    print(s.completion_suggestions)
  8. Quickstart with pytubefix

    main

    To download a YouTube video using pytubefix, import the YouTube class and the on_progress CLI utility. You can initialize a YouTube object with a URL and provide an on_progress_callback to track download progress. Use yt.streams.get_highest_resolution() to select the best quality stream and call .download() to save the file.

    from pytubefix import YouTube
    from pytubefix.cli import on_progress
     
    url = input("URL >")
     
    yt = YouTube(url, on_progress_callback = on_progress)
    print(yt.title)
     
    ys = yt.streams.get_highest_resolution()
    ys.download()
  9. Use the pytubefix CLI to download videos

    main

    The pytubefix CLI allows you to interact with YouTube videos and playlists directly from your terminal. By default, running the command with a URL downloads the highest resolution progressive stream.

    $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo
  10. Initialize a Playlist object

    main

    To work with YouTube playlists, import the Playlist class from pytubefix. You can initialize a Playlist object using either a direct playlist URL or a URL for a specific video that is part of a playlist.

    from pytubefix import Playlist
    
    # Using a playlist URL
    p = Playlist('https://www.youtube.com/playlist?list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n')
    
    # Using a video link that belongs to a playlist
    p = Playlist('https://www.youtube.com/watch?v=41qgdwd3zAg&list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n')
  11. Download a specific stream

    main

    Once you have identified a stream (either by filtering or by its unique itag), you can download it using the .download() method. You can retrieve a specific stream using .get_by_itag(itag_number) before calling download.

    # Get a specific stream by its itag and download it
    stream = yt.streams.get_by_itag(22)
    stream.download()