yt-dlp下载B站视频等相关cdn修改

生活 · 19 天前 · 13 人浏览

1.使用yt-dlp pip安装,使用方法见官方说明,或者ai一下
2.b站下载视频有个cdn源的问题,要修改一下源,这里使用一个插件。

第一次用插件,没搞懂放哪,windows下,找到pip安装的yt-dlp的位置,
和它平行的目录,新建一个yt_dlp_plugins,再新建一个插件类型的目录(如extractor)把对应的py插件放里面。

最终结构应该是:
..xx\Python3xx\Lib\site-packages
....yt_dlp
......ytdlp的本体文件
....yt_dlp_plugins
......extractor
........插件.py

最后可以使用 yt-dlp --verbose 验证一下插件加载情况。


T-DLP下载各大网站视频教程(简明教程)
Option to select Bilibili CDN / server for faster downloads

# Filename: yt_dlp_plugins/extractor/bilibili_hostname.py

from yt_dlp.extractor.bilibili import BiliBiliIE
from urllib.parse import urlparse, urlunparse

class BilibiliHostnameIE(BiliBiliIE):
    """
    A yt-dlp plugin to replace ANY hostname in Bilibili video URLs.
    
    It inherits the original BiliBiliIE, runs its logic, and then
    unconditionally overwrites the hostname for all format URLs.
    """
    # Override _VALID_URL to ensure yt-dlp prioritizes this plugin for Bilibili links
    _VALID_URL = BiliBiliIE._VALID_URL

    def _real_extract(self, url):
        # ================================================================
        # 🔧 CONFIGURATION: Specify the new hostname you want to use
        # ================================================================
        
        NEW_HOSTNAME = 'upos-sz-mirroraliov.bilivideo.com' # <-- CHANGE THE NEW HOSTNAME HERE
        
        # ================================================================

        # Call the original extractor's method to get the video info
        info_dict = super()._real_extract(url)

        # Check if the 'formats' key exists in the returned info
        if not info_dict.get('formats'):
            self.to_screen('[Bilibili Hostname] No formats found in video info. Skipping.')
            return info_dict

        replaced_count = 0
        # Iterate through all available video and audio formats
        for f in info_dict['formats']:
            if f.get('url'):
                try:
                    # Safely parse the original URL
                    parsed_url = urlparse(f['url'])
                    
                    # Unconditionally replace the hostname if it's different
                    if parsed_url.netloc != NEW_HOSTNAME:
                        new_parsed_url = parsed_url._replace(netloc=NEW_HOSTNAME)
                        f['url'] = urlunparse(new_parsed_url)
                        replaced_count += 1

                except Exception as e:
                    self.report_warning(f'[Bilibili Hostname] Error processing URL: {f["url"]}. Details: {e}')

        if replaced_count > 0:
            self.to_screen(f'[Bilibili Hostname] Replaced hostname for {replaced_count} format(s).')

        # Return the modified info_dict
        return info_dict
Theme Jasmine by Kent Liao