首页 > 解决方案 > 使用 python youtube_dl 从 youtube 下载 .mp3/webm 格式的音乐/视频的问题

问题描述

所以,这不是我在 youtube 教程上找到的代码(我现在找不到)。

from __future__ import unicode_literals
import youtube_dl
import os
from sys import argv

# Download data and config

download_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(title)s.%(ext)s',
    'nocheckcertificate': True,
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

# Song Directory
if not os.path.exists('Songs'):
    os.mkdir('Songs')
else:
    os.chdir('Songs')

# Download Songs
with youtube_dl.YoutubeDL(download_options) as dl:
    with open('..\\' + argv[1], 'r') as f:
        for song_url in f:
            dl.download([song_url])

它首先下载“.webm”文件(视频),然后正确转换为 mp3,然后删除原始“.webm”视频,我不希望它删除它,当我在 CMD 中运行它时显示“删除原始文件 .webm (传递 -k 保留),但我不知道在哪里传递 -k (我不是程序员,我只是复制了代码)

提前致谢!

标签: pythoncmdmp3youtube-dlwebm

解决方案


你需要传递一个额外的参数

这是从 youtube_dl github 复制的

--postprocessor-args ARGS        Give these arguments to the postprocessor
-k, --keep-video                 Keep the video file on disk after the post-
                                 processing; the video is erased by default

你可以在这里查看如何传递选项

我已经测试过这个语法,它对我有用(Darude Sandstorm)

   download_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(title)s.%(ext)s',
    'nocheckcertificate': True,
    'keepvideo': True,
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192'
    }]
}

推荐阅读