ytdlp 下载具有固定输出路径的视频

问题描述 投票:0回答:1

默认情况下,ytdl 会向文件添加扩展名,我试图避免这种情况。

我创建了下面的函数来将视频文件准确地保存在

output_path
(将被其他一些函数进一步使用)。

import logging
import yt_dlp as youtube_dl
from typing import Callable, Any, Optional
import os

def download_video(url: str, output_path: str, progress_hook_func: Callable[[dict], Any] = lambda d: None):
    downloaded_file_path: Optional[str] = None

    def _progress_hook(d):
        nonlocal downloaded_file_path
        progress_hook_func(d)
        if d['status'] != 'finished':
            return
        downloaded_file_path = d['filename']

    ydl_opts = {
        'format': 'bestvideo[height<=720]+bestaudio/best[height<=720]',
        'outtmpl': output_path,
        'quiet': True,  # Suppress console output
        'progress_hooks': [_progress_hook],
        'logger': logging.Logger("quiet", level=60),
        'postprocessors': []
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    if downloaded_file_path is not None and downloaded_file_path != output_path:
        os.rename(downloaded_file_path, output_path)

def test():
    download_video(r"https://www.youtube.com/watch?v=Ot2IGEPbe4I", "test", lambda d: print(d))

if __name__ == '__main__':
    test()

但是,有一个错误:

File "C:\Users\USER\PycharmProjects\pythonProject\srcs\algo\download_videos.py", line 60, in download_video
    os.rename(downloaded_file_path, output_path)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.f251.webm' -> 'test'

'filename'
并不是真正的文件名,它是一个类似临时文件的路径。我检查了工作目录并将其保存为
'test.webp'
而不是
'test.f251.webm'

如何将视频保存到固定路径且不带扩展名?

python youtube-dl yt-dlp
1个回答
0
投票

要使用 ytdlp 将视频下载到 Python 中的固定输出路径,可以使用以下步骤: 如果尚未安装,请安装 ytdlp。您可以使用 pip install yt-dlp 安装它。 使用以下Python代码:`

import yt_dlp

def download_video_with_fixed_path(url, output_path):
    ydl_opts = {
        'outtmpl': output_path + '/%(title)s.%(ext)s'
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

# Replace 'your_video_url' with the actual URL of the video
# and 'your_output_path' with the desired output path
video_url = 'your_video_url'
output_path = 'your_output_path'
download_video_with_fixed_path(video_url, output_path)`
© www.soinside.com 2019 - 2024. All rights reserved.