### Advanced YouTube Object Instantiation with Callbacks and Proxies (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/quickstart Demonstrates advanced instantiation of a YouTube object, including optional arguments for progress callbacks, completion callbacks, proxy settings, and OAuth configurations. These enhance control over the download process and authentication. ```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 (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/quickstart Imports the necessary YouTube class from the pytubefix library to begin interacting with YouTube videos. ```python from pytubefix import YouTube ``` -------------------------------- ### Instantiate YouTube Object and Get Title/Thumbnail (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/quickstart Creates a YouTube object from a video URL and retrieves its title and thumbnail URL. This is a fundamental step for accessing video metadata. ```python yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') print(yt.title) print(yt.thumbnail_url) ``` -------------------------------- ### Install Proxy Handler - Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/helpers Installs a proxy handler for network requests. It takes a dictionary of proxy settings and configures the URL opener to use these proxies. ```python from urllib import request from typing import Dict def install_proxy(proxy_handler: Dict[str, str]) -> None: proxy_support = request.ProxyHandler(proxy_handler) opener = request.build_opener(proxy_support) request.install_opener(opener) ``` -------------------------------- ### Download Stream Example (Python) Source: https://pytubefix.readthedocs.io/en/latest/user/streams This example demonstrates how to select a specific stream by its 'itag' and then download it to the local file system. It assumes a 'yt' object representing a YouTube video has already been initialized. ```python >>> stream = yt.streams.get_by_itag(22) >>> stream.download() ``` -------------------------------- ### Perform YouTube Search and Get Result Count (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/search This example shows how to initialize a Search object with a query and then check the total number of available results. It also illustrates how the results are initially presented as YouTube objects. Requires the pytubefix library. ```python from pytubefix import Search s = Search('YouTube Rewind') print(len(s.results)) print(s.results) ``` -------------------------------- ### Get Video URLs from a Channel using pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/channel Demonstrates how to retrieve a list of URLs for videos within a channel. The example shows fetching the first three video URLs using slicing. ```python for url in c.video_urls[:3]: print(url.watch_url) ``` -------------------------------- ### Download YouTube Video using pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/index This Python snippet demonstrates how to use the pytubefix library to download a YouTube video. It shows how to instantiate a YouTube object, access stream information, get the highest resolution stream, and download it. It also includes an example of using a progress callback. ```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() ``` -------------------------------- ### Setup Logger - Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/helpers Configures a logger instance with specified level and optional file logging. It sets up a formatter for log messages and can direct logs to both the console and a file. ```python import logging from typing import Optional def setup_logger(level: int = logging.ERROR, log_filename: Optional[str] = None) -> None: """Create a configured instance of logger. :param int level: Describe the severity level of the logs to handle. """ fmt = "[%(asctime)s] %(levelname)s in %(module)s: %(message)s" date_fmt = "%H:%M:%S" formatter = logging.Formatter(fmt, datefmt=date_fmt) # https://github.com/pytube/pytube/issues/163 logger = logging.getLogger("pytubefix") logger.setLevel(level) stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) if log_filename is not None: file_handler = logging.FileHandler(log_filename) file_handler.setFormatter(formatter) logger.addHandler(file_handler) ``` -------------------------------- ### Logging System Info During Download Source: https://pytubefix.readthedocs.io/en/latest/user/info An example of how to integrate `pytubefix.info()` with Python's logging module to record system details, pytubefix version, and download progress for a YouTube video. ```python >>> 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 >>> ``` -------------------------------- ### Access Video Title - Python Source: https://pytubefix.readthedocs.io/en/latest/user/quickstart Retrieves the title of the YouTube video from the YouTube object. ```python yt.title ``` -------------------------------- ### Access Thumbnail URL - Python Source: https://pytubefix.readthedocs.io/en/latest/user/quickstart Retrieves the URL of the thumbnail image for the YouTube video from the YouTube object. ```python yt.thumbnail_url ``` -------------------------------- ### Get System and Pytubefix Info Source: https://pytubefix.readthedocs.io/en/latest/user/info Retrieves a dictionary containing information about the operating system, Python version, and pytubefix version. This is useful for debugging and logging. ```python >>> 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'}} >>> ``` -------------------------------- ### Get Video Description (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the video description. It prioritizes the 'shortDescription' from 'videoDetails', falls back to OAuth if enabled, and then attempts to extract from the TV client structure if the description is not found. ```python @property def description(self) -> str: """Get the video description. :rtype: str """ description = self.vid_info.get("videoDetails", {}).get("shortDescription") if self.use_oauth == True: description = self.vid_engagement_items()[2]['expandableVideoDescriptionBodyRenderer']['descriptionBodyText']['runs'][0]['text'] if description is None: # TV client structure results = self.vid_details_content() for c in results: if 'videoSecondaryInfoRenderer' in c: description = c['videoSecondaryInfoRenderer']['attributedDescription']['content'] break return description ``` -------------------------------- ### Instantiate YouTube Object - Python Source: https://pytubefix.readthedocs.io/en/latest/user/quickstart Creates a YouTube object by providing a video URL. This object can then be used to access video details and download streams. Supports optional callbacks, proxies, and OAuth settings for advanced usage. ```python yt = YouTube('http://youtube.com/watch?v=2lAe1cqCOXo') ``` ```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 ) ``` -------------------------------- ### Extract YouTube Replayed Heatmap with Pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/keymoments This code snippet shows how to retrieve replayed heatmap data for a YouTube video using pytubefix. Ensure the pytubefix library is installed. The function takes a YouTube video URL as input and returns a list of dictionaries, where each dictionary contains the start time, duration, and normalized intensity of a segment. ```python from pytubefix import YouTube yt = YouTube("https://www.youtube.com/watch?v=rSKMYc1CQHE") print(yt.replayed_heatmap) ``` -------------------------------- ### Send HTTP GET Request in Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/request The get function performs an HTTP GET request to a specified URL. It utilizes the internal _execute_request function, allowing for optional extra headers and a timeout. The function returns the response body as a UTF-8 decoded string. ```python def get(url, extra_headers=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): """Send an http GET request. :param str url: The URL to perform the GET request for. :param dict extra_headers: Extra headers to add to the request :rtype: str :returns: UTF-8 encoded string of response """ if extra_headers is None: extra_headers = {} response = _execute_request(url, headers=extra_headers, timeout=timeout) return response.read().decode("utf-8") ``` -------------------------------- ### pytubefix.helpers.setup_logger Source: https://pytubefix.readthedocs.io/en/latest/api Creates and configures an instance of a logger with a specified severity level and optional log filename. ```APIDOC ## Function pytubefix.helpers.setup_logger ### Description Create a configured instance of logger. ### Method N/A (Function) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **level** (int) - Optional - Describe the severity level of the logs to handle. Default is 40 (WARNING). * **log_filename** (str | None) - Optional - The name of the log file. If None, logs to console. ### Request Example ```python from pytubefix import helpers import logging # Setup logger to log WARNING and above to console helpers.setup_logger(level=logging.WARNING) # Setup logger to log INFO and above to a file helpers.setup_logger(level=logging.INFO, log_filename="pytubefix.log") ``` ### Response #### Success Response (200) None (This function configures logging, does not return data) #### Response Example N/A ``` -------------------------------- ### Get Video Author (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the author of the video. It attempts to get the author from 'videoDetails' and also supports fetching it via OAuth. ```python @property def author(self) -> str: """Get the video author. :rtype: str """ # TODO: Implement correctly for the TV client _author = self.vid_info.get("videoDetails", {}).get("author", "unknown") if self.use_oauth == True: _author = self.vid_engagement_items()[0]['videoDescriptionHeaderRenderer']['channel']['simpleText'] self._author = _author return self._author ``` -------------------------------- ### Create pytubefix Channel Object from URL Source: https://pytubefix.readthedocs.io/en/latest/user/channel Demonstrates how to initialize a Channel object using a direct channel URL or a link to the channel's video page. This object serves as an entry point for channel-related operations. ```python c = Channel('https://www.youtube.com/@ProgrammingKnowledge/featured') ``` ```python c = Channel('https://www.youtube.com/@ProgrammingKnowledge/videos') ``` -------------------------------- ### Extract Chapter Start Label - Python Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/chapters This snippet demonstrates how to retrieve the start time label for the first chapter of a YouTube video using pytubefix. It accesses the 'start_label' attribute of the first Chapter object. ```python print(yt.chapters[0].start_label) ``` -------------------------------- ### Initialize YouTube Class Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Constructs a YouTube object for interacting with YouTube videos. It accepts a URL and various optional parameters for callbacks, proxies, and OAuth authentication. It initializes internal states and extracts video information. ```python class YouTube: """Core developer interface for pytubefix.""" def __init__( self, url: str, client: str = InnerTube().client_name, on_progress_callback: Optional[Callable[[Any, bytes, int], None]] = None, on_complete_callback: Optional[Callable[[Any, Optional[str]], None]] = None, proxies: Optional[Dict[str, str]] = None, use_oauth: bool = False, allow_oauth_cache: bool = True, token_file: Optional[str] = None, oauth_verifier: Optional[Callable[[str, str], None]] = None, use_po_token: Optional[bool] = False, po_token_verifier: Optional[Callable[[None], Tuple[str, str]]] = None, ): """Construct a :class:`YouTube `. :param str url: A valid YouTube watch URL. :param str client: (Optional) A YouTube client, Available: WEB, WEB_EMBED, WEB_MUSIC, WEB_CREATOR, WEB_SAFARI, ANDROID, ANDROID_MUSIC, ANDROID_CREATOR, ANDROID_VR, ANDROID_PRODUCER, ANDROID_TESTSUITE, IOS, IOS_MUSIC, IOS_CREATOR, MWEB, TV, TV_EMBED, MEDIA_CONNECT. :param func on_progress_callback: (Optional) User defined callback function for stream download progress events. :param func on_complete_callback: (Optional) User defined callback function for stream download complete events. :param dict proxies: (Optional) A dict mapping protocol to proxy address which will be used by pytube. :param bool use_oauth: (Optional) Prompt the user to authenticate to YouTube. If allow_oauth_cache is set to True, the user should only be prompted once. :param bool allow_oauth_cache: (Optional) Cache OAuth and Po tokens locally on the machine. Defaults to True. These tokens are only generated if use_oauth is set to True as well. :param str token_file: (Optional) Path to the file where the OAuth and Po tokens will be stored. Defaults to None, which means the tokens will be stored in the pytubefix/__cache__ directory. :param Callable oauth_verifier: (optional) Verifier to be used for getting oauth tokens. Verification URL and User-Code will be passed to it respectively. (if passed, else default verifier will be used) """ # js fetched by js_url self._js: Optional[str] = None # the url to the js, parsed from watch html self._js_url: Optional[str] = None # content fetched from innertube/player self._vid_info: Optional[Dict] = None self._vid_details: Optional[Dict] = None # the html of /watch?v= self._watch_html: Optional[str] = None self._embed_html: Optional[str] = None # inline js in the html containing self._player_config_args: Optional[Dict] = None self._age_restricted: Optional[bool] = None self._fmt_streams: Optional[List[Stream]] = None self._initial_data = None self._metadata: Optional[YouTubeMetadata] = None # video_id part of /watch?v= self.video_id = extract.video_id(url) self.watch_url = f"https://youtube.com/watch?v={self.video_id}" self.embed_url = f"https://www.youtube.com/embed/{self.video_id}" self.client = client # oauth can only be used by the TV and TV_EMBED client. self.client = 'TV' if use_oauth else self.client self.fallback_clients = ['TV', 'IOS'] self._signature_timestamp: dict = {} self._visitor_data = None # Shared between all instances of `Stream` (Borg pattern). self.stream_monostate = Monostate( on_progress=on_progress_callback, on_complete=on_complete_callback, youtube=self ) if proxies: install_proxy(proxies) self._author = None self._title = None self._original_title = None self._publish_date = None ``` -------------------------------- ### Create and Initialize pytubefix Channel Object Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/channel Demonstrates how to import the Channel class and create a Channel object using a YouTube channel URL. This is the first step to interacting with channel data. ```python from pytubux import Channel c = Channel('https://www.youtube.com/@ProgrammingKnowledge/featured') ``` ```python from pytubux import Channel c = Channel('https://www.youtube.com/@ProgrammingKnowledge/videos') ``` -------------------------------- ### Search Class Initialization for YouTube Queries Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/contrib/search The Search class is designed to initialize and execute YouTube searches. It accepts a search query and various optional parameters for client customization, proxy configuration, OAuth authentication, and filter application. The constructor sets up the necessary attributes for performing a search, including handling authentication tokens and specifying search criteria. ```python class Search: def __init__( self, query: str, client: str = InnerTube().client_name, proxies: Optional[Dict[str, str]] = None, use_oauth: bool = False, allow_oauth_cache: bool = True, token_file: Optional[str] = None, oauth_verifier: Optional[Callable[[str, str], None]] = None, use_po_token: Optional[bool] = False, po_token_verifier: Optional[Callable[[None], Tuple[str, str]]] = None, filters: Optional[Filter] = None ): """Initialize Search object. :param str query: Search query provided by the user. :param dict proxies: (Optional) A dict mapping protocol to proxy address which will be used by pytube. :param bool use_oauth: (Optional) Prompt the user to authenticate to YouTube. If allow_oauth_cache is set to True, the user should only be prompted once. :param bool allow_oauth_cache: (Optional) Cache OAuth tokens locally on the machine. Defaults to True. These tokens are only generated if use_oauth is set to True as well. :param str token_file: (Optional) Path to the file where the OAuth tokens will be stored. Defaults to None, which means the tokens will be stored in the pytubefix/__cache__ directory. :param Callable oauth_verifier: (optional) Verifier to be used for getting OAuth tokens. Verification URL and User-Code will be passed to it respectively. (if passed, else default verifier will be used) :param bool use_po_token: (Optional) Prompt the user to use the proof of origin token on YouTube. It must be sent with the API along with the linked visitorData and then passed as a `po_token` query parameter to affected clients. If allow_oauth_cache is set to True, the user should only be prompted once. :param Callable po_token_verifier: (Optional) Verified used to obtain the visitorData and po_token. The verifier will return the visitorData and po_token respectively. (if passed, else default verifier will be used) :param Filter filters: (Optional) Apply filters when searching. Can be used: `upload_date`, `type`, `duration`, `features`, `sort_by`. features can be combined into a list with other parameters of the same type. """ self.query = query self.client = client self.use_oauth = use_oauth self.allow_oauth_cache = allow_oauth_cache self.token_file = token_file self.oauth_verifier = oauth_verifier self.use_po_token = use_po_token ``` -------------------------------- ### Get YouTube Channel Playlists with pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/channel_playlists This snippet shows how to fetch all playlists belonging to a specific YouTube channel. It requires the pytubefix library and takes a channel URL as input, returning a list of Playlist objects. ```python from pytubefix import Channel ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists) ``` -------------------------------- ### Get YouTube Video Objects from Playlist Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/channel_playlists Demonstrates how to retrieve a list of YouTube video objects for a given playlist from a channel. Requires the pytube library. It takes a channel URL as input and outputs a list of YouTube objects. ```python from pytube import Channel ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists[0].videos) ``` -------------------------------- ### Initialize InnerTube Client and Search Filters Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/contrib/search Initializes the InnerTube client for interacting with YouTube's API and sets up search filters. It handles both dictionary-based and protobuf-encoded filters, with a deprecation warning for the former. Dependencies include 'InnerTube', 'install_proxy', 'Filter', 'encode_protobuf', and logging utilities. ```python self.po_token_verifier = po_token_verifier self._innertube_client = InnerTube( client='WEB', use_oauth=self.use_oauth, allow_cache=self.allow_oauth_cache, token_file=self.token_file, oauth_verifier=self.oauth_verifier, use_po_token=self.use_po_token, po_token_verifier=self.po_token_verifier ) # The first search, without a continuation, is structured differently # and contains completion suggestions, so we must store this separately self._initial_results = None self._results = {} self._completion_suggestions = None # Used for keeping track of query continuations so that new results # are always returned when get_next_results() is called self._current_continuation = None if proxies: install_proxy(proxies) self.filter = None if filters: logger.debug("Filters found, starting combination") # TODO: if isinstance(filters, dict): logging.warning("This filter implementation is obsolete and will be removed soon. " "Please refer to the documentation for the new implementation. " "https://pytubefix.readthedocs.io/en/latest/user/search.html") filter_protobuf = Filter() filter_protobuf.set_filters(filters) self.filter = filter_protobuf.get_filters_params() else: self.filter = encode_protobuf(filters.merge()) logger.debug(f"Filter encoded in protobuf: {self.filter}") ``` -------------------------------- ### Initialize Formatted Video Streams Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Initializes and returns a list of formatted video streams. It processes the stream manifest, applies descrambling and potential PoToken, and handles JavaScript player requirements, including fetching updated JS if necessary. Dependencies include `extract`, `InnerTube`, and `Stream`. ```python @property def fmt_streams(self): """Returns a list of streams if they have been initialized. If the streams have not been initialized, finds all relevant streams and initializes them. """ self.check_availability() if self._fmt_streams: return self._fmt_streams self._fmt_streams = [] stream_manifest = extract.apply_descrambler(self.streaming_data) inner_tube = InnerTube(self.client) if self.po_token: extract.apply_po_token(stream_manifest, self.vid_info, self.po_token) if inner_tube.require_js_player: # If the cached js doesn't work, try fetching a new js file # https://github.com/pytube/pytube/issues/1054 try: extract.apply_signature(stream_manifest, self.vid_info, self.js, self.js_url) except exceptions.ExtractError: # To force an update to the js file, we clear the cache and retry self._js = None self._js_url = None pytubefix.__js__ = None pytubefix.__js_url__ = None extract.apply_signature(stream_manifest, self.vid_info, self.js, self.js_url) # build instances of :class:`Stream ` # Initialize stream objects for stream in stream_manifest: video = Stream( stream=stream, monostate=self.stream_monostate, po_token=self.po_token, video_playback_ustreamer_config=self.video_playback_ustreamer_config ) self._fmt_streams.append(video) self.stream_monostate.title = self.title self.stream_monostate.duration = self.length return self._fmt_streams ``` -------------------------------- ### Get YouTube Video URLs from Playlist Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/channel_playlists Shows how to obtain a list of URLs for videos within a specific playlist of a YouTube channel. This functionality relies on the pytube library. The input is a channel URL, and the output is a list of video URLs. ```python from pytube import Channel ch = Channel('https://www.youtube.com/@Alanwalkermusic') print(ch.playlists[0].video_urls) ``` -------------------------------- ### Define Chapter Class in Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/chapters Defines the Chapter class to hold chapter details like title, start time in seconds, duration, and a list of ChapterThumbnail objects. It parses chapter data and provides a formatted start time label. ```python # Native python imports from datetime import timedelta from typing import List [docs] class Chapter: """Container for chapters tracks.""" title: str start_seconds: int duration: int # in seconds thumbnails: List[ChapterThumbnail] def __init__(self, chapter_data: dict, duration: int): data = chapter_data['chapterRenderer'] self.title = data['title']['simpleText'] self.start_seconds = int(data['timeRangeStartMillis'] / 1000) self.duration = duration thumbnails_data = data.get('thumbnail', {}).get('thumbnails', []) self.thumbnails = [ ChapterThumbnail( width=thumb['width'], height=thumb['height'], url=thumb['url'] ) for thumb in thumbnails_data ] @property def start_label(self) -> str: return str(timedelta(seconds=self.start_seconds)) def __repr__(self): return f'' ``` -------------------------------- ### pytubefix.request.head Source: https://pytubefix.readthedocs.io/en/latest/api Fetches the headers returned by an HTTP GET request. ```APIDOC ## HEAD /website/pytubefix/request/head ### Description Fetches the headers returned by an HTTP GET request. ### Method HEAD ### Endpoint /website/pytubefix/request/head ### Parameters #### Query Parameters - **url** (str) - Required - The URL to perform the GET request for. ### Response #### Success Response (200) - **headers** (dict) - Dictionary of lowercase headers. #### Response Example ```json { "headers": { "content-type": "application/json", "content-length": "123" } } ``` ``` -------------------------------- ### Logging Environment Details with Pytubefix during Download Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/info Integrates Pytubefix's `info()` function with Python's logging module to log detailed system information alongside download progress and video titles. This comprehensive logging aids in post-execution analysis and error tracking. ```python import logging from pytubefix import YouTube, info 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() logging.info(f"System Information: Pytubefix v{system_info['Pytubefix']}, Python{system_info['Python']}, OS {system_info['OS']}") logging.info(f"Video title: {yt.title}") ``` -------------------------------- ### Get Video Title Source: https://pytubefix.readthedocs.io/en/latest/api Retrieves the title of the YouTube video. ```APIDOC ## GET /title ### Description Retrieves the title of the YouTube video. ### Method GET ### Endpoint /title ### Parameters This endpoint does not take any parameters. ### Response #### Success Response (200) - **title** (str) - The title of the YouTube video. #### Response Example ```json "Example Video Title" ``` ``` -------------------------------- ### Create Pytubefix Playlist Object (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/playlist Demonstrates how to create a Playlist object by initializing it with a YouTube playlist URL or a video URL from a playlist. This object serves as a container for YouTube videos within the playlist. ```python from pytubefix import Playlist p = Playlist('https://www.youtube.com/playlist?list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n') p = Playlist('https://www.youtube.com/watch?v=41qgdwd3zAg&list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n') ``` -------------------------------- ### Configure and Use Proxies with Pytubefix (Python) Source: https://pytubefix.readthedocs.io/en/latest/user/proxy This Python code snippet demonstrates how to set up and utilize proxy servers when initializing a YouTube object with Pytubefix. It specifies HTTP and HTTPS proxy details, allowing the library to route requests through the provided proxy address. This is useful for circumventing IP-based restrictions. ```python from pytububefix import YouTube proxy = { "http": "socks5://proxy_address", "https": "socks5://proxy_address" } url = "url" yt = YouTube(url, proxies=proxy) print(yt.title) ys = yt.streams.get_highest_resolution() ys.download() ``` -------------------------------- ### pytubefix.request.get Source: https://pytubefix.readthedocs.io/en/latest/api Sends an HTTP GET request to the specified URL with optional extra headers. ```APIDOC ## GET /website/pytubefix/request/get ### Description Sends an HTTP GET request to the specified URL with optional extra headers. ### Method GET ### Endpoint /website/pytubefix/request/get ### Parameters #### Query Parameters - **url** (str) - Required - The URL to perform the GET request for. - **extra_headers** (dict) - Optional - Extra headers to add to the request. - **timeout** (object) - Optional - Timeout for the request. ### Response #### Success Response (200) - **content** (str) - UTF-8 encoded string of the response. #### Response Example ```json { "content": "Response body as a string" } ``` ``` -------------------------------- ### Download a Specific Stream using Pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/streams Demonstrates how to select a stream by its itag and then download it to the local filesystem. The `download()` method can accept various arguments for customization, as detailed in the API reference. ```python from pytubefix import YouTube yt = YouTube('https://www.youtube.com/watch?v=dQw4w9WgXcQ') stream = yt.streams.get_by_itag(22) stream.download() ``` -------------------------------- ### Get Video Width Source: https://pytubefix.readthedocs.io/en/latest/api Retrieves the width of the video in pixels. Returns None if the value is not available. ```APIDOC ## GET /width ### Description Retrieves the width of the video in pixels. Returns None if the value is not available. ### Method GET ### Endpoint /width ### Parameters This endpoint does not take any parameters. ### Response #### Success Response (200) - **width** (int or None) - The width of the video in pixels, or None if not available. #### Response Example ```json 1920 ``` ``` -------------------------------- ### Chapter Object Source: https://pytubefix.readthedocs.io/en/latest/_sources/api Represents a chapter within a YouTube video, including title, start time, and thumbnail. ```APIDOC ## Chapter Object ### Description Represents a chapter in a YouTube video, including its title, start time, and an associated thumbnail. ### Class `pytubefix.chapters.Chapter` ### Members - `title` (str): The title of the chapter. - `start_time` (int): The start time of the chapter in seconds. - `thumbnail` (ChapterThumbnail): An object representing the thumbnail for this chapter. ### Request Example ```python # Example usage would involve accessing this from a YouTube object's chapters attribute # Assuming 'chapter_data' is an instance of Chapter print(f'Chapter Title: {chapter_data.title}') print(f'Start Time: {chapter_data.start_time}s') print(f'Thumbnail URL: {chapter_data.thumbnail.url}') ``` ### Response #### Success Response (Object Attributes) - `title` (str): The title of the chapter. - `start_time` (int): The start time in seconds. - `thumbnail` (ChapterThumbnail): Thumbnail object for the chapter. #### Response Example ```json { "title": "Introduction", "start_time": 0, "thumbnail": { "url": "https://i.ytimg.com/vi/example/hqdefault.jpg", "width": 480, "height": 360 } } ``` ``` -------------------------------- ### Create Playlist Object from URL - Python Source: https://pytubefix.readthedocs.io/en/latest/user/playlist Initializes a Playlist object by providing a YouTube playlist URL. This allows you to work with all the videos contained within that specific playlist. ```python p = Playlist('https://www.youtube.com/playlist?list=PLS1QulWo1RIaJECMeUT4LFwJ-ghgoSH6n') ``` -------------------------------- ### Create Mock HTML JSON - Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/helpers Generates a gzipped JSON file containing sample HTML responses for a given YouTube video ID. This is used for testing purposes to mock YouTube's responses. ```python import gzip import json import os import logging from typing import Dict, Any from pytubefix import YouTube logger = logging.getLogger("pytubefix") def create_mock_html_json(vid_id) -> Dict[str, Any]: """Generate a json.gz file with sample html responses. :param str vid_id YouTube video id :return dict data Dict used to generate the json.gz file """ from pytubefix import YouTube gzip_filename = f'yt-video-{vid_id}-html.json.gz' # Get the pytube directory in order to navigate to /tests/mocks pytube_dir_path = os.path.abspath( os.path.join( os.path.dirname(__file__), os.path.pardir ) ) pytube_mocks_path = os.path.join(pytube_dir_path, 'tests', 'mocks') gzip_filepath = os.path.join(pytube_mocks_path, gzip_filename) yt = YouTube(f'https://www.youtube.com/watch?v={vid_id}') html_data = { 'url': yt.watch_url, 'js': yt.js, 'embed_html': yt.embed_html, 'watch_html': yt.watch_html, 'vid_info': yt.vid_info } logger.info(f'Outputing json.gz file to {gzip_filepath}') with gzip.open(gzip_filepath, 'wb') as f: f.write(json.dumps(html_data).encode('utf-8')) return html_data ``` -------------------------------- ### Get Video Length in Seconds (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the length of the video in seconds. Ensures the video is available before fetching the length. ```python @property def length(self) -> int: """Get the video length in seconds. :rtype: int """ self.check_availability() return int(self.vid_info.get('videoDetails', {}).get('lengthSeconds')) ``` -------------------------------- ### Initialize Search and Get Result Count Source: https://pytubefix.readthedocs.io/en/latest/user/search Shows how to create a Search object with a query and inspect the number of initial results available. The `.results` attribute holds the first batch of search results. Requires the pytubefix library. ```python >>> from pytubefix import Search >>> s = Search('YouTube Rewind') >>> len(s.results) 17 >>> s.results [\ , \ , \ ..., >>> ``` -------------------------------- ### Pytubefix YouTube Methods Source: https://pytubefix.readthedocs.io/en/latest/genindex Documentation for methods of the pytubefix.YouTube object. ```APIDOC ## Pytubefix YouTube Methods ### Description Methods available for interacting with YouTube video objects. ### Methods - **register_on_complete_callback()** - Registers a callback for download completion. - **register_on_progress_callback()** - Registers a callback for download progress. ``` -------------------------------- ### Get Video Average Rating (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the average rating of the video from 'videoDetails'. Returns None if the rating is not available. ```python @property def rating(self) -> float: """Get the video average rating. :rtype: float """ return self.vid_info.get("videoDetails", {}).get("averageRating") ``` -------------------------------- ### Target Directory Determination - Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/helpers Determines the target directory for downloads, handling relative or absolute paths, and creating the directory if it doesn't exist. If no path is provided, it defaults to the current working directory. ```python import os from typing import Optional def target_directory(output_path: Optional[str] = None) -> str: """ Function for determining target directory of a download. Returns an absolute path (if relative one given) or the current path (if none given). Makes directory if it does not exist. :type output_path: str :rtype: str :returns: An absolute directory path as a string. """ if output_path: if not os.path.isabs(output_path): output_path = os.path.join(os.getcwd(), output_path) else: output_path = os.getcwd() os.makedirs(output_path, exist_ok=True) return output_path ``` -------------------------------- ### Get Video Keywords (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves a list of keywords associated with the video from 'videoDetails'. Returns an empty list if no keywords are found. ```python @property def keywords(self) -> List[str]: """Get the video keywords. :rtype: List[str] """ return self.vid_info.get('videoDetails', {}).get('keywords', []) ``` -------------------------------- ### Get Video Channel ID (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the channel ID of the video's uploader from 'videoDetails'. Returns None if the channel ID is not available. ```python @property def channel_id(self) -> str: """Get the video poster's channel id. :rtype: str """ return self.vid_info.get('videoDetails', {}).get('channelId', None) ``` -------------------------------- ### Iterate Through YouTube Playlists using pytubefix Source: https://pytubefix.readthedocs.io/en/latest/user/search This example shows how to retrieve and iterate through YouTube playlists found by a search query using pytubefix. It imports Search, initializes it, and then loops through the results, printing the playlist URL for each. ```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 ``` -------------------------------- ### Get YouTube Video Title - Python Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/streams Retrieves the title of a YouTube video. This property is intended to return the video's title as a string. ```python @property def title(self,) -> str: """Get title of video :rtype: str :returns: Youtube video title """ ``` -------------------------------- ### Get Video View Count (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the number of views for the video. It handles different data structures for view counts, including those obtained via OAuth. ```python @property def views(self) -> int: """Get the number of the times the video has been viewed. :rtype: int """ view = int(self.vid_info.get("videoDetails", {}).get("viewCount", "0")) if self.use_oauth == True: simple_text = self.vid_engagement_items()[0]['videoDescriptionHeaderRenderer']['views']['simpleText'] view = int(''.join([char for char in simple_text if char.isdigit()])) if not view: results = self.vid_details_content() for c in results: if 'videoPrimaryInfoRenderer' in c: simple_text = c['videoPrimaryInfoRenderer'][ 'viewCount'][ 'videoViewCountRenderer'][ 'viewCount'][ 'simpleText'] view = int(''.join([char for char in simple_text if char.isdigit()])) break return view ``` -------------------------------- ### Get Video Likes (Python) Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/__main__ Retrieves the number of likes for the video. Supports fetching likes via OAuth or by parsing content details, with error handling for missing data. ```python @property def likes(self): """Get the video likes :rtype: str """ if self.use_oauth == True: return self.vid_engagement_items()[0]['videoDescriptionHeaderRenderer']['factoid'][0]['factoidRenderer']['value']['simpleText'] try: likes = '0' contents = self.vid_details_content() for c in contents: if 'videoPrimaryInfoRenderer' in c: likes = c['videoPrimaryInfoRenderer'][ 'videoActions'][ 'menuRenderer'][ 'topLevelButtons'][ 0][ 'segmentedLikeDislikeButtonViewModel'][ 'likeButtonViewModel'][ 'likeButtonViewModel'][ 'toggleButtonViewModel'][ 'toggleButtonViewModel'][ 'defaultButtonViewModel'][ 'buttonViewModel'][ 'accessibilityText'] break return ''.join([char for char in likes if char.isdigit()]) except (KeyError, IndexError) as e: ``` -------------------------------- ### Manual PO Token Integration with Pytubefix (Python) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/po_token This snippet shows how to manually integrate a PO Token obtained from a browser session into Pytubefix. The `use_po_token=True` argument is used, and it's assumed you have manually acquired both the PO Token and visitorData from browser developer tools. ```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() ``` -------------------------------- ### Get Length of Stream Query Results Source: https://pytubefix.readthedocs.io/en/latest/_modules/pytubefix/query Returns the total number of streams available in the query results. This allows for easy checking of the quantity of streams using the `len()` function. ```python def __len__(self) -> int: return len(self.fmt_streams) ``` -------------------------------- ### Redirect YouTube Download to Stdout (Bash) Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/buffer A bash command to execute a Python script (main.py) that downloads YouTube content and redirects its output to standard output. This output can then be piped to other command-line tools for processing. ```bash $ python3 main.py | ffplay -i - ``` ```bash $ python3 main.py | ffmpeg -i - -acodec libmp3lame output.mp3 ``` ```bash $ python3 main.py | less ``` ```bash $ python3 main.py > output.webm ``` ```bash $ python3 main.py | nc 192.168.1.100 5000 ``` ```bash $ python3 playlist.py | ffplay -i - ``` ```bash $ python3 main.py | hexdump -C ``` -------------------------------- ### Retrieving and Displaying XML Captions Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/captions Illustrates how to get a specific caption track and access its raw XML formatted content. This is useful for detailed inspection or custom parsing. ```python caption = yt.captions['a.en'] print(caption.xml_captions) ``` -------------------------------- ### Pytubefix Helper Methods Source: https://pytubefix.readthedocs.io/en/latest/genindex Documentation for helper methods in Pytubefix. ```APIDOC ## Pytubefix Helper Methods ### Description Utility methods provided by the pytubefix.helpers module. ### Methods - **regex_search()** - Performs a search using regular expressions. - **reset_cache()** - Resets the cache. ``` -------------------------------- ### Download Audio as M4a using pytubefix Source: https://pytubefix.readthedocs.io/en/latest/_sources/user/m4a This snippet demonstrates how to download the audio-only stream of a YouTube video in .m4a format using the pytubefix library. It initializes a YouTube object with a provided URL and an optional progress callback, retrieves the audio stream, and then downloads it. Ensure pytubefix is installed. ```python from pytubux 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_audio_only() ys.download() ```