2024最新python使用yt-dlp

1.获取yt的cookie

1)google浏览器下载Get cookies.txt LOCALLY插件

https://chromewebstore.google.com/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc
在这里插入图片描述

2)导出cookie或者点击Copy复制粘贴到对应的cookie文件即可

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

推荐使用cookies方式,因为:
更安全,不需要存储密码
避免频繁登录导致的验证码问题
可以访问账号订阅的内容
支持年龄限制视频的下载
记住要定期更新cookies以确保其有效性。

2.yt-dlp下载yt-dlp的GitHub地址

1)使用Pycharm(2024.3)进行代码demo编写

在这里插入图片描述

2)使用的python版本3.9.13

在这里插入图片描述

3)Pycharm下载对应的第三方库yt-dlp

在这里插入图片描述
在这里插入图片描述

4)使用命令进行下载

pip install yt-dlp

在这里插入图片描述

提示pip警告
[notice] A new release of pip is available: 23.2.1 -> 24.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip
更新就行了
python.exe -m pip install --upgrade pip

在这里插入图片描述

5)复制cookie到根目录

在这里插入图片描述

5)python代码

import yt_dlp
from pathlib import Path
import os


def yt_test(url):
    try:
        # 创建下载目录
        video_path = Path("downloads/video")
        audio_path = Path("downloads/audio")
        video_path.mkdir(parents=True, exist_ok=True)
        audio_path.mkdir(parents=True, exist_ok=True)

        # yt-dlp 基础配置
        common_opts = {
            'cookiefile': r'www.youtube.com_cookies.txt',
            'quiet': False,
            'no_warnings': False,
            'verbose': True,
            'proxy': 'http://127.0.0.1:10809',
            'socket_timeout': 30,
            'retries': 3,
            'nocheckcertificate': True,
            'prefer_insecure': True
        }

        print("开始下载视频...")
        print(f"使用cookies文件: {common_opts['cookiefile']}")

        # 视频下载选项
        video_opts = {
            **common_opts,
            'format': 'best[ext=mp4][height<=720]/best[height<=720]/best',
            'outtmpl': str(video_path / '%(title)s.%(ext)s'),
        }

        # 音频下载选项
        audio_opts = {
            **common_opts,
            'format': 'bestaudio[ext=m4a]/bestaudio',
            'outtmpl': str(audio_path / '%(title)s.%(ext)s'),
        }

        # 获取视频信息
        print("正在获取视频信息...")
        with yt_dlp.YoutubeDL(common_opts) as ydl:
            info = ydl.extract_info(url, download=False)
            title = info['title']
            duration = info['duration']
            thumbnail = info['thumbnail']

            print(f"视频标题: {title}")
            print(f"视频时长: {duration // 60}:{duration % 60:02d}")
            print(f"缩略图URL: {thumbnail}")

        # 下载视频
        print("\n开始下载视频文件...")
        with yt_dlp.YoutubeDL(video_opts) as ydl:
            ydl.download([url])

        # 下载音频
        print("\n开始下载音频文件...")
        with yt_dlp.YoutubeDL(audio_opts) as ydl:
            ydl.download([url])

        # 获取下载后的文件路径
        video_file = next(video_path.glob(f"{title}.*"))
        audio_file = next(audio_path.glob(f"{title}.*"))

        print("\n下载完成!")
        print(f"视频文件: {video_file}")
        print(f"音频文件: {audio_file}")

        return {
            "status": "success",
            "title": title,
            "duration": f"{duration // 60}:{duration % 60:02d}",
            "thumbnail": thumbnail,
            "video_path": str(video_file),
            "audio_path": str(audio_file)
        }

    except Exception as e:
        print(f"\n下载过程中出错: {str(e)}")
        return {"status": "error", "message": str(e)}


if __name__ == "__main__":
    # 测试URL
    test_url = "******.com/watch?v=_KFzaJSxBcY"

    print("测试")
    print("-" * 50)
    print(f"测试URL: {test_url}")
    print("-" * 50)

    result = yt_test(test_url)

    if result["status"] == "success":
        print("\n测试成功!")
        print("-" * 50)
        print(f"标题: {result['title']}")
        print(f"时长: {result['duration']}")
        print(f"视频文件: {result['video_path']}")
        print(f"音频文件: {result['audio_path']}")
    else:
        print("\n测试失败!")
        print("-" * 50)
        print(f"错误信息: {result['message']}")

6)运行测试

在这里插入图片描述

3.注意事项

1)配置

猫: 常用7890
V2: 常用 10808/10809
S: 常用1080

2)yt-dlp配置

common_opts = {
‘cookiefile’: r’cookies.txt’,
‘quiet’: False,
‘no_warnings’: False,
‘verbose’: True,
#和上方的端口进行对应
‘proxy’: ‘http://127.0.0.1:10809’,
‘socket_timeout’: 30,
‘retries’: 3,
‘nocheckcertificate’: True,
‘prefer_insecure’: True
}

3) 可能会报的错误(Please install or provide the path using --ffmpeg-location)

WARNING: sqRSzq1J46A: writing DASH m4a. Only som
e players support this container. Install ffmpeg
to fix this automatically
ERROR: ffprobe and ffmpeg not found. Please inst
all or provide the path using --ffmpeg-location
Traceback (most recent call last):
File “C:\Users\Administrator\AppData\Local\Pro
grams\Python\Python39\lib\site-packages\yt_dlp\Y
outubeDL.py”, line 3701, in run_pp
files_to_delete, infodict = pp.run(infodict)
File “C:\Users\Administrator\AppData\Local\Pro
grams\Python\Python39\lib\site-packages\yt_dlp\p
ostprocessor\common.py”, line 22, in run
ret = func(self, info, *args, **kwargs)
File “C:\Users\Administrator\AppData\Local\Pro
grams\Python\Python39\lib\site-packages\yt_dlp\p
ostprocessor\common.py”, line 127, in wrapper
return func(self, info)
File “C:\Users\Administrator\AppData\Local\Pro
grams\Python\Python39\lib\site-packages\yt_dlp\p
ostprocessor\ffmpeg.py”, line 493, in run
filecodec = self.get_audio_codec(path)
File “C:\Users\Administrator\AppData\Local\Pro
grams\Python\Python39\lib\site-packages\yt_dlp\p
ostprocessor\ffmpeg.py”, line 241, in get_audio_
codec
raise PostProcessingError(‘ffprobe and ffmpe
g not found. Please install or provide the path
using --ffmpeg-location’)
yt_dlp.utils.PostProcessingError: ffprobe and ff
mpeg not found. Please install or provide the pa
th using --ffmpeg-location

解决方法:下载并配置对应的环境变量即可ffmpeg和ffprobe

https://github.com/GyanD/codexffmpeg/releases/tag/2024-12-11-git-a518b5540d
在这里插入图片描述
在这里插入图片描述
解压到对应的目录
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

添加完成环境变量后在终端打开输入ffmpeg和ffprobe测试环境是否配置成功
在这里插入图片描述
在这里插入图片描述

4.demo项目github地址

https://github.com/unkownc/python_demo/tree/main
在这里插入图片描述

### 如何使用 `yt-dlp` 参数进行视频下载 为了更好地理解并利用 `yt-dlp` 的强大功能,在Python环境中可以通过设置不同的选项来自定义下载行为。下面提供了一个详细的例子,说明如何通过调整参数实现特定需求。 #### 基础配置 最简单的形式如下所示: ```python import yt_dlp def basic_download(url): ydl_opts = { 'format': 'bestvideo+bestaudio/best', 'outtmpl': '%(title)s.%(ext)s' } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) ``` 这段代码会自动选择最佳画质和音质组合,并保存文件名为视频标题加上扩展名[^1]。 #### 自定义输出路径与格式 如果希望指定更复杂的输出目录结构或更改默认的文件命名方式,则可以修改 `'outtmpl'` 键对应的模板字符串。例如: ```python ydl_opts = { ... 'outtmpl': '/path/to/save/%(uploader)s/%(title)s-%(id)s.%(ext)s', } ``` 这将会创建一个按照上传者名称分类的文件夹树状结构存储所下载的内容[^2]。 #### 下载音频而非视频 对于只关心声音而不需图像的情况,可专门提取音频流: ```python ydl_opts = { 'format': 'm4a/bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download(['http://example.com/some_audio_file']) ``` 上述片段不仅指定了优先考虑高质量的音频格式(`m4a`),还加入了后处理器(Postprocessor),用于进一步转换成MP3格式。 #### 添加进度条显示 为了让用户能够实时跟踪下载状态,可以在初始化时加入额外的日志记录器(Logging Handler): ```python from pprint import pprint class MyLogger(object): def debug(self, msg): pass def warning(self, msg): print(msg) def error(self, msg): print(msg) def my_hook(d): if d['status'] == 'finished': print('Done downloading, now converting ...') ydl_opts = { 'progress_hooks': [my_hook], 'logger': MyLogger(), } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.example.com/video']) ``` 此部分实现了自定义日志打印逻辑以及完成事件回调函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值