### AsyncYouTube Quick Start Example Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Demonstrates basic asynchronous usage of AsyncYouTube to fetch and print all available streams for a given URL. Supports OAuth for age-restricted content. Requires asyncio and pytubefix. ```python import asyncio from pytubefix import AsyncYouTube URL = "YOUR_VIDEO_URL" async def main(): # Initialize AsyncYouTube with OAuth to handle age-restricted content yt = AsyncYouTube(URL, use_oauth=True, allow_oauth_cache=True) # Fetch all available streams asynchronously streams = await yt.streams() print("Available Streams:") for stream in streams: print(stream) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Install pytubefix from local source Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/install.md After cloning or downloading the source, navigate to the directory and install pytubefix using pip. ```bash cd pytubefix python -m pip install . ``` -------------------------------- ### Get Channel Playlists Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel_playlists.md Initialize a Channel object with the channel's URL and print its playlists attribute to get a list of playlist objects. Ensure the pytubefix library is installed. ```python from pytubefix import Channel ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists) ``` -------------------------------- ### Install pytubefix using pip Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/install.md Use this command to install the pytubefix library directly from the Python Package Index. ```bash pip install pytubefix ``` -------------------------------- ### Get Chapter Start Label Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/chapters.md Retrieve the formatted start time string for a chapter using its start_label attribute. This is useful for displaying timestamps. ```python print(yt.chapters[0].start_label) ``` -------------------------------- ### AI-Assisted Contribution Example 1 Source: https://github.com/juanbindez/pytubefix/blob/main/CONTRIBUTING.md Example of an 'Assisted-by' tag indicating contribution from ChatGPT. ```text Assisted-by: ChatGPT:GPT-5.5 [OpenAI] ``` -------------------------------- ### Download Highest Resolution Progressive Stream with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md Use this command to download the highest resolution progressive stream of a YouTube video. No additional setup is required beyond having pytubefix installed. ```bash $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo ``` -------------------------------- ### AI-Assisted Contribution Example 3 Source: https://github.com/juanbindez/pytubefix/blob/main/CONTRIBUTING.md Example of an 'Assisted-by' tag indicating contribution from GitHub Copilot. ```text Assisted-by: GitHub Copilot:GPT-5 [GitHub] [OpenAI] ``` -------------------------------- ### Get All Info - Pytubefix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/info.md Retrieve a dictionary containing OS, Python, and Pytubefix versions. Useful for comprehensive environment checks. ```pycon >>> from pytubefix import info >>> >>> print(info()) {'OS': {'linux'}, 'Python': {'3.11.6 (main, Apr 10 2024, 17:26:07) [GCC 13.2.0]'}, 'Pytubefix': {'7.3.1'}} ``` -------------------------------- ### AI-Assisted Contribution Example 2 Source: https://github.com/juanbindez/pytubefix/blob/main/CONTRIBUTING.md Example of an 'Assisted-by' tag indicating contribution from Claude. ```text Assisted-by: Claude:Opus-4 [Anthropic] ``` -------------------------------- ### Get YouTube Video Chapters Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/chapters.md Import the YouTube class and retrieve the chapters attribute for a given video URL. Ensure the pytubefix library is installed. ```python from pytubefix import YouTube url = 'https://www.youtube.com/watch?v=kRzgCylePjk' yt = YouTube(url) print(yt.chapters) ``` -------------------------------- ### Get All Caption Tracks Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/captions.md Initialize a YouTube object and access all available caption tracks. This is the first step to working with subtitles. ```python from pytubefix import YouTube yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') subtitles = yt.captions print(subtitles) ``` -------------------------------- ### Check pytubefix Version Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md To check the installed version of pytubefix, use the -V flag. ```bash $ pytubefix -V ``` -------------------------------- ### Get Video URLs for Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel_playlists.md Use this to get a list of URLs for each video in a playlist. Ensure the Channel class is imported. ```python ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists[0].video_urls) ``` -------------------------------- ### Automatic PO Token Generation with Node.js Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/po_token.md Use this snippet to automatically generate a PO Token by setting the client to 'WEB'. Node.js is installed as a dependency. ```python from pytubefix import YouTube url = input("url >") yt = YouTube(url, 'WEB') print(yt.title) ys = yt.streams.get_highest_resolution() ys.download() ``` -------------------------------- ### Get YouTube Objects for Playlist Videos Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel_playlists.md Use this to get a list of YouTube objects for each video in a playlist. Ensure the Channel class is imported. ```python ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists[0].videos) ``` -------------------------------- ### Get Operating System Info - Pytubefix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/info.md Extract and print only the operating system information from the info() dictionary. Useful for environment-specific logic. ```pycon >>> from pytubefix import info >>> >>> system_info = info() >>> >>> print(f"Operational System: {system_info['OS']}") Operational System: linux ``` -------------------------------- ### Download YouTube Video with Progress Callback Source: https://github.com/juanbindez/pytubefix/blob/main/docs/index.md This snippet demonstrates how to download a YouTube video using pytubefix, including displaying download progress. Ensure you have pytubefix installed and import the necessary modules. ```python 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() ``` -------------------------------- ### List Available Subtitles with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md To get a list of all available subtitle (caption) codes for a video, use the --list-captions flag. ```bash $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo --list-captions ``` -------------------------------- ### Clone pytubefix repository Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/install.md Clone the official GitHub repository to get the source code for pytubefix. ```bash git clone git://github.com/JuanBindez/pytubefix.git ``` -------------------------------- ### Convert Buffer Content Format with ffmpeg-python Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Converts the buffer content from one audio/video format to another using the 'ffmpeg-python' library. This example converts MP3 input to WAV output, reading from stdin and writing to stdout. ```python import ffmpeg input_stream = ffmpeg.input("pipe:", format="mp3") output_stream = ffmpeg.output(input_stream, "output.wav") fmpeg.run(output_stream, pipe_stdin=True, input=buffer.read()) ``` -------------------------------- ### Commit Message with AI Assistance and DCO Source: https://github.com/juanbindez/pytubefix/blob/main/CONTRIBUTING.md This example shows the correct placement of the 'Assisted-by' tag between the contributor's 'Signed-off-by' lines in a commit message. ```text Improve cipher validation logic Signed-off-by: John Doe Assisted-by: ChatGPT:GPT-5.5 [OpenAI] Signed-off-by: John Doe ``` -------------------------------- ### Get Channel Name Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Retrieves the name of a YouTube channel given its URL. Requires the pytubefix library. ```python from pytubefix import Channel c = Channel("https://www.youtube.com/@ProgrammingKnowledge/featured") print(f'Channel name: {c.channel_name}') ``` -------------------------------- ### Get XML Formatted Captions Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/captions.md Retrieve the raw XML formatted caption data for a specific caption track. ```python caption.xml_captions ``` -------------------------------- ### Get Video Title Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/quickstart.md Access the 'title' attribute of the YouTube object to retrieve the video's title. ```python yt.title ``` -------------------------------- ### Get Video URLs from a Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Retrieve and print the URLs of the first three videos in a playlist. Assumes a Playlist object 'p' has already been created. ```python >>> for url in p.video_urls[:3]: >>> print(url) ['https://www.youtube.com/watch?v=41qgdwd3zAg', 'https://www.youtube.com/watch?v=Lbs7vmx3YwU', 'https://www.youtube.com/watch?v=YtX-Rmoea0M'] ``` -------------------------------- ### Get Initial YouTube Search Results Count Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Instantiate a Search object with a query and check the length of the `.results` attribute to determine the number of videos in the initial search results. This provides a quick way to gauge the quantity of available videos. ```python >>> from pytubefix import Search >>> s = Search('YouTube Rewind') >>> len(s.results) 17 >>> s.results [ , , ... ] >>> ``` -------------------------------- ### DCO Signed-off-by Line Example Source: https://github.com/juanbindez/pytubefix/blob/main/CONTRIBUTING.md This is the format for the 'Signed-off-by' line that is automatically appended by 'git commit -s', certifying your understanding and responsibility for the contribution. ```text Signed-off-by: Your Name ``` -------------------------------- ### Retrieve Only Videos from Search Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Use the `.videos` attribute to exclusively get YouTube video objects from a search query. Ensure `pytubefix.Search` is imported. ```python >>> from pytubefix import Search >>> >>> s = Search('YouTube Rewind') >>> >>> print(s.videos) [, , , , , , , , , , , , , , , ] >>> ``` -------------------------------- ### Get Pytubefix Version - Pytubefix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/info.md Extract and print only the Pytubefix version from the info() dictionary. Essential for verifying library version in use. ```pycon >>> from pytubefix import info >>> >>> system_info = info() >>> >>> print(f"Pytubefix Version: {system_info['Pytubefix']}") Pytubefix Version: 7.3.1 ``` -------------------------------- ### Get Autocomplete Suggestions Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Access autocomplete suggestions associated with a search query. This is useful for providing real-time search assistance to users. ```python >>> s.completion_suggestions [ 'can this video get 1 million dislikes', 'youtube rewind 2020 musical', ... ] ``` -------------------------------- ### Encrypt Buffer Content with Fernet Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Encrypts the data read from the buffer using Fernet symmetric encryption. Requires the 'cryptography' library to be installed. The generated key should be securely stored. ```python from cryptography.fernet import Fernet key = Fernet.generate_key() cipher = Fernet(key) encrypted_data = cipher.encrypt(buffer.read()) print("Encrypted data:", encrypted_data) ``` -------------------------------- ### Upload Buffer Content to API Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Uploads the content read from the buffer to a specified API endpoint using a POST request with the 'requests' library. Requires the 'requests' library to be installed. ```python import requests response = requests.post( "http://example.com/upload", files={"file": buffer.read()} ) print(response.status_code) ``` -------------------------------- ### Reset Cache in PyTubeFix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/auth.md To reset the cache, import and call `reset_cache()` or set `allow_oauth_cache` to `False` during YouTube initialization. This example demonstrates resetting the cache before initializing YouTube. ```python from pytubefix import YouTube from pytubefix.helpers import reset_cache reset_cache() url = input("url") yt = YouTube(url, use_oauth=True, allow_oauth_cache=True) print(yt.title) ys = yt.streams.get_highest_resolution() ys.download() ``` -------------------------------- ### Get Default Audio Streams Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/dubbed_streams.md Use `get_default_audio_track()` to retrieve only the streams that contain the default audio language for a video. This is useful when you only need the primary audio. ```python yt = YouTube('https://www.youtube.com/watch?v=g_VxOIlg7q8') for s in yt.streams.get_default_audio_track(): print(f"{s.itag} {s.includes_multiple_audio_tracks} {s.audio_track_name}") ``` -------------------------------- ### Extract Key Moments from YouTube Video Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/keymoments.md Use the `key_moments` attribute to retrieve a list of significant time-stamped events within a YouTube video. Ensure the pytubefix library is installed. ```python from pytubefix import YouTube yt = YouTube("https://www.youtube.com/watch?v=-xNR_1WJQ-E") print(yt.key_moments) ``` -------------------------------- ### Display pytubefix CLI Help Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md To see a list of all available command-line options for pytubefix, use the --help flag. ```bash $ pytubefix --help ``` -------------------------------- ### Initialize YouTube Object with Callbacks and Proxies Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/quickstart.md Instantiate a YouTube object with optional arguments for progress callbacks, completion callbacks, proxies, and OAuth settings for advanced usage. ```python yt = YouTube( 'http://youtube.com/watch?v=2lAe1cqCOXo', on_progress_callback=progress_func, on_complete_callback=complete_func, proxies=my_proxies, use_oauth=False, allow_oauth_cache=True ) ``` -------------------------------- ### Import YouTube Class Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/quickstart.md Import the necessary YouTube class from the pytubefix library to begin. ```python from pytubux import YouTube ``` -------------------------------- ### Extract Replayed Heatmap Data from YouTube Video Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/keymoments.md Access the `replayed_heatmap` attribute to get data on video replay intensity, including start time, duration, and normalized intensity. This is useful for analyzing viewer engagement patterns. ```python from pytubefix import YouTube yt = YouTube("https://www.youtube.com/watch?v=rSKMYc1CQHE") print(yt.replayed_heatmap) ``` -------------------------------- ### Initialize YouTube Object Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/quickstart.md Create a YouTube object by providing the video URL. This object will be used to access video details and download streams. ```python yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') ``` -------------------------------- ### List Available Streams with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md To view all available streams for a YouTube video, use the --list flag. This helps in identifying different resolutions and formats. ```bash $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo --list ``` -------------------------------- ### Create Playlist Object from URL Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Initialize a Playlist object by providing a YouTube playlist URL. ```python >>> p = Playlist('https://www.youtube.com/playlist?list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n') ``` -------------------------------- ### Logging with Pytubefix Info and Download Progress Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/info.md Integrates Pytubefix's info() with Python's logging module to record system details and download progress. This is valuable for debugging in production or cloud environments. ```pycon >>> import logging >>> from pytubefix import YouTube, info >>> from pytubefix.cli import on_progress >>> >>> logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') >>> >>> system_info = info() >>> >>> def on_progress_with_logging(stream, chunk, bytes_remaining): ... progress = 100 - (bytes_remaining / stream.filesize * 100) ... logging.info(f"Download progress: {progress:.2f}%") ... >>> url = "https://www.youtube.com/watch?v=9bZkp7q19f0" >>> >>> yt = YouTube(url, on_progress_callback=on_progress_with_logging) >>> >>> ys = yt.streams.get_highest_resolution() >>> ys.download() '/home/PSY - GANGNAM STYLE(강남스타일) MV.mp4' >>> >>> logging.info(f"System Information: Pytubefix v{system_info['Pytubefix']}, Python{system_info['Python']}, OS {system_info['OS']}") 2024-11-14 23:00:10,876 - INFO - System Information: Pytubefix v8.3.2, Python3.11.6 (main, Apr 10 2024, 17:26:07) [GCC 13.2.0], OS linux >>> logging.info(f"Video title: {yt.title}") 2024-11-14 23:00:10,877 - INFO - Video title: PSY - GANGNAM STYLE(강남스타일) M/V >>> >>> >>> ``` -------------------------------- ### Download Specific Stream with Callbacks Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Demonstrates downloading a specific stream (e.g., 360p MP4) with progress and completion callbacks. The `download()` method is synchronous and should be used with callbacks for non-blocking behavior. ```python import asyncio from pytubix import AsyncYouTube URL = "YOUR_VIDEO_URL" async def main(): def on_progress(stream, chunk, bytes_remaining): total = stream.filesize percent = (1 - bytes_remaining / total) * 100 print(f"\rProgress: {percent:.2f}%", end="") def on_complete(stream, file_path): print(f"\n√ Done downloading: {file_path}") yt = AsyncYouTube(URL, use_oauth=True, allow_oauth_cache=True) yt.register_on_progress_callback(on_progress) yt.register_on_complete_callback(on_complete) stream = await yt.get_stream_by_itag(18) # 360p MP4 progressive stream print(f"Downloading: {await yt.title()}") stream.download(filename="my_video.mp4") # Blocking call by design if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Import Playlist Class Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Import the Playlist class from the pytubefix library to begin working with playlists. ```python >>> from pytubefix import Playlist ``` -------------------------------- ### Get Video URLs from a Channel Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel.md Access the URLs of videos within a Channel object. The `video_urls` attribute provides a list of URLs, which can be iterated to get individual watch URLs. ```python >>> for url in c.video_urls[:3]: >>> print(url.watch_url) ['https://www.youtube.com/watch?v=tMqMU1U2MCU', 'https://www.youtube.com/watch?v=YBfInrtWq8Y', 'https://www.youtube.com/watch?v=EP9WrMw6Gzg'] ``` -------------------------------- ### Build Playback Report with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md When filing a bug report, use the --build-playback-report flag to bundle up the current state, which helps others replay the issue. ```bash $ pytubefix --build-playback-report ``` -------------------------------- ### Create AsyncYouTube Instance from Video ID Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Initializes an AsyncYouTube instance directly from a video ID and retrieves all available streams. ```python import asyncio from pytubix import AsyncYouTube VIDEO_ID = "YOUR_VIDEO_ID" async def main(): yt = AsyncYouTube.from_id(VIDEO_ID, use_oauth=True, allow_oauth_cache=True) streams = await yt.streams() print("Streams fetched from Video ID:") for s in streams: print(s) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Create Playlist Object from Video Link in Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Initialize a Playlist object using a video URL that belongs to a specific playlist. ```python >>> p = Playlist('https://www.youtube.com/watch?v=41qgdwd3zAg&list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n') ``` -------------------------------- ### Get Thumbnail URL Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/quickstart.md Access the 'thumbnail_url' attribute of the YouTube object to retrieve the URL of the video's thumbnail. ```python yt.thumbnail_url ``` -------------------------------- ### Specify Output Directory for Downloads Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Downloads the highest resolution MP4 video and saves it to a specified output directory. Requires pytubefix and its on_progress callback. ```python from pytubefix import YouTube from pytubefix.cli import on_progress url = "url" yt = YouTube(url, on_progress_callback=on_progress) ys = yt.streams.get_highest_resolution() ys.download(output_path="path/to/directory") ``` -------------------------------- ### Pytubefix Project Structure - Security Module Source: https://github.com/juanbindez/pytubefix/blob/main/CONTEXT.md Illustrates the directory structure for the botGuard module, responsible for handling bot protection mechanisms. ```tree botGuard/ ├── __init__.py ├── bot_guard.py ├── vm/ └── botGuard.js ``` -------------------------------- ### Download to Buffer and Redirect to Stdout Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Downloads audio-only stream data into an in-memory buffer and then redirects it to standard output. This is useful for piping the data to other command-line tools. ```python from pytubefix import YouTube from pytubefix import Buffer buffer = Buffer() url = "URL" yt = YouTube(url) ys = yt.streams.get_audio_only() buffer.download_in_buffer(ys) buffer.redirect_to_stdout() ``` -------------------------------- ### Add Authentication for Age-Restricted Videos Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/auth.md Use `use_oauth=True` and `allow_oauth_cache=True` when initializing YouTube to download age-restricted videos. The authentication prompt will appear when `download()` is called. ```python from pytubefix import YouTube from pytubefix.cli import on_progress url = input("url") yt = YouTube(url, use_oauth=True, allow_oauth_cache=True, on_progress_callback = on_progress) print(yt.title) ys = yt.streams.get_highest_resolution() ys.download()# you will only receive the authentication request if you call the download() method ``` -------------------------------- ### Manual PO Token Acquisition and Usage Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/po_token.md Acquire a PO Token and visitorData manually from browser developer tools and pass them to pytubefix using `use_po_token=True`. Ensure you are logged out of YouTube. ```python from pytubefix import YouTube url = input("url >") yt = YouTube(url, use_po_token=True) print(yt.title) ys = yt.streams.get_highest_resolution() ys.download() ``` -------------------------------- ### Retrieve Only Playlists from Search Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Iterate through the `.playlist` attribute to get YouTube playlist objects from a search query. Each playlist object contains a `playlist_url` attribute. ```python >>> from pytubefix import Search >>> >>> s = Search('python tutorial') >>> >>> >>> for p in s.playlist: ... print('url', p.playlist_url) ... url https://www.youtube.com/playlist?list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU url https://www.youtube.com/playlist?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3 url https://www.youtube.com/playlist?list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB url https://www.youtube.com/playlist?list=PLTjRvDozrdlxj5wgH4qkvwSOdHLOCx10f url https://www.youtube.com/playlist?list=PLBZBJbE_rGRWeh5mIBhD-hhDwSEDxogDg url https://www.youtube.com/playlist?list=PLGjplNEQ1it8-0CmoljS5yeV-GlKSUEt0 ``` -------------------------------- ### Retrieve Only Shorts from Search Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Use the `.shorts` attribute to exclusively get YouTube Shorts objects from a search query. Note that shorts are of the same class as videos. ```python >>> from pytubefix import Search >>> >>> s = Search('YouTube Rewind') >>> >>> print(s.shorts) [, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] >>> ``` -------------------------------- ### Get All Dubbed Audio Streams Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/dubbed_streams.md Use `get_extra_audio_track()` to retrieve all streams that include multiple audio tracks. This method helps identify streams with dubbed versions. ```python yt = YouTube('https://www.youtube.com/watch?v=g_VxOIlg7q8') for s in yt.streams.get_extra_audio_track(): print(f"{s.itag} {s.includes_multiple_audio_tracks} {s.audio_track_name}") ``` -------------------------------- ### Download Audio Stream with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md To download only the audio stream of a YouTube video (defaulting to AAC/mp4), use the -a flag. ```bash $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo -a ``` -------------------------------- ### Create Channel Object from URL Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel.md Initialize a Channel object using a YouTube channel's URL. This allows you to interact with the channel's content. ```python >>> c = Channel('https://www.youtube.com/@ProgrammingKnowledge/featured') ``` ```python >>> c = Channel('https://www.youtube.com/@ProgrammingKnowledge/videos') ``` -------------------------------- ### Download All Videos from a Channel Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel.md Iterate through all videos in a Channel object and download the highest resolution stream for each. This requires initializing a Channel object and looping through its `videos` attribute. ```python from pytubefix import Channel c = Channel("https://www.youtube.com/@ProgrammingKnowledge") print(f'Downloading videos by: {c.channel_name}') for video in c.videos: download = video.streams.get_highest_resolution().download() ``` -------------------------------- ### Download Video to Specific Directory Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/output_path.md Use the `output_path` argument in the `download` method to specify a custom directory for saving videos. Ensure the directory exists before downloading. ```python from pytubefix import YouTube from pytubefix.cli import on_progress url = "url" yt = YouTube(url, on_progress_callback = on_progress) ys = yt.streams.get_highest_resolution() ys.download(output_path="path/to/directory") ``` -------------------------------- ### Download pytubefix source tarball Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/install.md Download the source code archive for pytubefix from GitHub. ```bash curl -OL https://github.com/JuanBindez/pytubefix/tarball/master ``` -------------------------------- ### Import Channel Class in pytubefix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel.md Import the Channel class from the pytubefix library to begin working with YouTube channels. ```python >>> from pytubefix import Channel ``` -------------------------------- ### Retrieve Chapter Thumbnails Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/chapters.md Access the thumbnails attribute of a chapter object to get a list of associated thumbnail image URLs and dimensions. Note that thumbnails may not be available for all chapters. ```python print(yt.chapters[2].thumbnails) ``` -------------------------------- ### Get Dubbed Audio Streams by Name Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/dubbed_streams.md Filter dubbed streams by specifying the desired language name using `get_extra_audio_track_by_name()`. This allows you to select specific dubbed audio tracks. ```python yt = YouTube('https://www.youtube.com/watch?v=g_VxOIlg7q8') for s in yt.streams.get_extra_audio_track_by_name("German"): print(f"{s.itag} {s.includes_multiple_audio_tracks} {s.audio_track_name}") ``` -------------------------------- ### Pytubefix Project Structure - Core Modules Source: https://github.com/juanbindez/pytubefix/blob/main/CONTEXT.md This snippet shows the directory structure of the core pytubefix library, detailing the purpose of each main module. ```tree pytubefix/ ├── __init__.py # Package initialization ├── __main__.py # Main entry point and YouTube class ├── streams.py # Stream handling and processing ├── cipher.py # Signature cipher decryption ├── innertube.py # YouTube API interaction ├── extract.py # Data extraction utilities └── request.py # HTTP request management ``` -------------------------------- ### Get Channel Name using pytubefix Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/channel.md Retrieve the name of a YouTube channel by accessing the `channel_name` attribute of a Channel object. Ensure the Channel class is imported and the object is initialized with a valid channel URL. ```python from pytubefix import Channel c = Channel("https://www.youtube.com/@ProgrammingKnowledge/featured") print(f'Channel name: {c.channel_name}') ``` -------------------------------- ### Pytubefix Project Structure - Contributions Module Source: https://github.com/juanbindez/pytubefix/blob/main/CONTEXT.md Shows the directory structure for the contrib module, which contains supplementary features like search, playlists, and channels. ```tree contrib/ ├── search.py ├── playlist.py └── channel.py ``` -------------------------------- ### Pytubefix Project Structure - Adaptive Streaming Module Source: https://github.com/juanbindez/pytubefix/blob/main/CONTEXT.md Details the directory structure for the sabr module, which handles adaptive streaming functionalities. ```tree sabr/ ├── video_streaming/ ├── core/ └── proto.py ``` -------------------------------- ### Retrieve Video Chapters and Key Moments Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Fetches chapter information and key moments from a YouTube video asynchronously. ```python import asyncio from pytubix import AsyncYouTube URL = "YOUR_VIDEO_URL" async def main(): yt = AsyncYouTube(URL, use_oauth=True, allow_oauth_cache=True) chapters = await yt.chapters() key_moments = await yt.key_moments() print("Chapters:", chapters) print("Key Moments:", key_moments) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Download Audio-Only (.m4a) Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Downloads only the audio stream in .m4a format for a given YouTube URL. Requires the pytubefix library and its on_progress callback. ```python from pytubefix import YouTube from pytubefix.cli import on_progress url = "url" yt = YouTube(url, on_progress_callback=on_progress) print(yt.title) ys = yt.streams.get_audio_only() ys.download() ``` -------------------------------- ### Download a YouTube Stream Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/streams.md Select a stream by its itag and then download it to your local machine. Refer to the API documentation for available download arguments. ```python >>> stream = yt.streams.get_by_itag(22) >>> stream.download() ``` -------------------------------- ### Preview Buffer Content with hexdump Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Previews the raw hexadecimal content of the buffer using hexdump by piping the output of a Python script. The script should redirect buffer content to stdout. ```bash $ python3 main.py | hexdump -C ``` -------------------------------- ### Download All Videos from a Channel Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Downloads the highest resolution video for every video within a specified YouTube channel. Requires the pytubefix library. ```python from pytubefix import Channel c = Channel("https://www.youtube.com/@ProgrammingKnowledge") print(f'Downloading videos by: {c.channel_name}') for video in c.videos: video.streams.get_highest_resolution().download() ``` -------------------------------- ### Use OAuth Authentication for Downloads Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Downloads the highest resolution MP4 video using OAuth authentication, which can help handle age-restricted content. Requires pytubefix and its on_progress callback. Authentication is performed once. ```python from pytubefix import YouTube from pytubefix.cli import on_progress url = "url" yt = YouTube(url, use_oauth=True, allow_oauth_cache=True, on_progress_callback=on_progress) ys = yt.streams.get_highest_resolution() ys.download() # Authenticate once for subsequent downloads ``` -------------------------------- ### Print Subtitle Tracks in SRT Format Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Accesses a specific subtitle track (e.g., English) and generates its content in SRT format. Requires the pytubefix library. ```python from pytubefix import YouTube yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') caption = yt.captions['a.en'] print(caption.generate_srt_captions()) ``` -------------------------------- ### Play Playlist in Terminal with ffplay Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Plays an entire YouTube playlist's audio streams sequentially on the terminal using ffplay by piping the output of a Python script. The script should redirect buffer content to stdout for each video. ```bash $ python3 playlist.py | ffplay -i - ``` -------------------------------- ### List all available streams Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/streams.md Use this to list all available streams for a YouTube video. Note that higher quality streams are often split into separate audio and video tracks (DASH). ```python >>> yt.streams [ ... ] ``` -------------------------------- ### Download All Videos in a Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Iterate through all videos in a playlist and download the highest resolution stream for each. Requires user input for the playlist URL. ```python from pytubefix import Playlist from pytubefix.cli import on_progress url = input("url here >") pl = Playlist(url) for video in pl.videos: ys = video.streams.get_highest_resolution() ys.download() ``` -------------------------------- ### Download All Audio Streams in a Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/playlist.md Iterate through all videos in a playlist and download the audio-only stream for each, saving it as an MP3. Requires user input for the playlist URL. ```python from pytubefix import Playlist from pytubefix.cli import on_progress url = input("url here >") pl = Playlist(url) for video in pl.videos: ys = video.streams.get_audio_only() ys.download(mp3=True) ``` -------------------------------- ### Handle VideoUnavailable Exception Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/exceptions.md Use this pattern to catch VideoUnavailable exceptions when iterating through playlist videos. This allows your program to skip unaccessible videos and continue processing the rest of the playlist. ```python >>> from pytubefix import Playlist, YouTube >>> from pytubefix.exceptions import VideoUnavailable >>> playlist_url = 'https://youtube.com/playlist?list=special_playlist_id' >>> p = Playlist(playlist_url) >>> for url in p.video_urls: ... try: ... yt = YouTube(url) ... except VideoUnavailable: ... print(f'Video {url} is unavaialable, skipping.') ... else: ... print(f'Downloading video: {url}') ... yt.streams.first().download() ``` -------------------------------- ### Pytubefix Utility Modules Source: https://github.com/juanbindez/pytubefix/blob/main/docs/api.md Details the utility modules available in the Pytubefix library for various functionalities. ```APIDOC ## Pytubefix Utility Modules This section describes the utility modules that extend the functionality of the Pytubefix library. ### Extract Module for extracting information from YouTube URLs. ### Cipher Module for handling YouTube's cipher operations. ### Exceptions Custom exceptions raised by the Pytubefix library. ### Helpers Utility functions and helpers for various tasks. ### Request Module for handling HTTP requests to YouTube. ``` -------------------------------- ### Download Specific Subtitle with pytubefix CLI Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/cli.md Download a specific subtitle by its language code (e.g., 'en' for English) in SRT format using the -c flag. ```bash $ pytubefix https://www.youtube.com/watch?v=2lAe1cqCOXo -c en ``` -------------------------------- ### View Available Subtitles Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Retrieves and prints all available subtitle caption tracks for a given YouTube video. Requires the pytubefix library. ```python from pytubefix import YouTube yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') print(yt.captions) ``` -------------------------------- ### Download a Complete Playlist Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Downloads the audio-only stream for each video in a YouTube playlist. Requires the pytubefix library and its on_progress callback. ```python from pytubefix import Playlist from pytubefix.cli import on_progress url = "url" pl = Playlist(url) for video in pl.videos: ys = video.streams.get_audio_only() ys.download() ``` -------------------------------- ### View Buffer Content with less Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Allows viewing the buffer content in a pager like 'less' by piping the output of a Python script. The script should redirect buffer content to stdout. ```bash $ python3 main.py | less ``` -------------------------------- ### Pytubefix Core Objects Source: https://github.com/juanbindez/pytubefix/blob/main/docs/api.md Details the main objects provided by the Pytubefix library for interacting with YouTube data. ```APIDOC ## Pytubefix Objects This section outlines the primary objects available in the Pytubefix library for accessing and manipulating YouTube content. ### YouTube Object Represents a YouTube video or channel. ### KeyMomentsThumbnail Object Represents a thumbnail for key moments in a video. ### KeyMoments Object Represents the key moments of a video. ### Playlist Object Represents a YouTube playlist. ### Channel Object Represents a YouTube channel. ### Stream Object Represents a single stream (video/audio rendition) of a YouTube video. ### StreamQuery Object Provides methods for filtering and sorting available streams. ### Caption Object Represents a caption track for a YouTube video. ### CaptionQuery Object Provides methods for filtering and selecting caption tracks. ### Search Object Represents the results of a YouTube search. ### ChapterThumbnail Object Represents a thumbnail for video chapters. ### Chapter Object Represents a chapter within a YouTube video. ``` -------------------------------- ### Compress Buffer Content with gzip Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Compresses the data read from the buffer using gzip and saves it to a file. Requires the 'gzip' module, which is part of Python's standard library. ```python import gzip compressed_data = gzip.compress(buffer.read()) with open("compressed.gz", "wb") as file: file.write(compressed_data) ``` -------------------------------- ### Convert Audio to MP3 with ffmpeg Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/buffer.md Converts an audio stream to MP3 format using ffmpeg by piping the output of a Python script. The script should redirect buffer content to stdout. ```bash $ python3 main.py | ffmpeg -i - -acodec libmp3lame output.mp3 ``` -------------------------------- ### Basic Video Search Source: https://github.com/juanbindez/pytubefix/blob/main/README.md Performs a basic search for YouTube videos based on a query and prints their title, URL, and duration. Requires the pytubefix.Search class. ```python from pytubefix import Search results = Search('GitHub Issue Best Practices') for video in results.videos: print(f'Title: {video.title}') print(f'URL: {video.watch_url}') print(f'Duration: {video.length} sec') print('---') ``` -------------------------------- ### Search YouTube and Print Video Details Source: https://github.com/juanbindez/pytubefix/blob/main/docs/user/search.md Use the Search object to find videos based on a query and iterate through the results to print video titles, URLs, and durations. This is useful for automating YouTube searches and extracting basic video information. ```python >>> from pytubefix import Search >>> >>> results = Search('Github Issue Best Practices') >>> >>> for video in results.videos: ... print(f'Title: {video.title}') ... print(f'URL: {video.watch_url}') ... print(f'Duration: {video.length} sec') ... print('---') ... Title: Good Practices with GitHub Issues URL: https://youtube.com/watch?v=v1AeHaopAYE Duration: 406 sec --- Title: GitHub Issues Tips and Guidelines URL: https://youtube.com/watch?v=kezinXSoV5A Duration: 852 sec --- Title: 13 Advanced (but useful) Git Techniques and Shortcuts URL: https://youtube.com/watch?v=ecK3EnyGD8o Duration: 486 sec --- Title: Managing a GitHub Organization Tools, Tips, and Best Practices - Mark Matyas URL: https://youtube.com/watch?v=1T4HAPBFbb0 Duration: 1525 sec --- Title: Do you know the best way to manage GitHub Issues? URL: https://youtube.com/watch?v=OccRyzAS4Vc Duration: 534 sec --- >>> ```