You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的yt-dlp提取、选择并下载指定视频格式(解决报错)

解决yt-dlp指定格式下载的报错问题

错误原因

你调用process_ie_result传入的是单个格式字典,但该方法需要完整的视频信息字典(即extract_info返回的video_info),单个格式条目缺少extractor等必要字段,因此触发KeyError。

正确实现方式

方法1:通过format参数指定格式ID下载

直接在YoutubeDL配置中设置format参数,指定目标格式的format_id,同时配置输出路径和文件名,最后调用download方法即可:

import yt_dlp

# 初始化下载配置
ydl_opts = {
    'outtmpl': '/your/output/path/%(title)s.%(ext)s',  # 自定义输出路径与文件名模板
}

with yt_dlp.YoutubeDL(ydl_opts) as ydlp:
    url = 'https://www.youtube.com/watch?v=d95PPykB2vE'
    video_info = ydlp.extract_info(url, download=False)
    
    # 筛选目标格式:示例为720p、无音频的webm格式
    target_format = next(f for f in video_info['formats'] 
                        if f['height'] == 720 and f['vcodec'] != 'none' and f['acodec'] == 'none' and f['ext'] == 'webm')
    
    # 更新配置,指定要下载的格式ID
    ydl_opts['format'] = target_format['format_id']
    
    # 执行下载
    ydlp.download([url])

方法2:修改视频信息字典后调用process_ie_result

若坚持使用process_ie_result,需将选中的格式放入视频信息字典的requested_formats字段,再传入完整字典:

import yt_dlp

# 配置输出路径
ydlp = yt_dlp.YoutubeDL({'outtmpl': '/your/output/path/%(title)s.%(ext)s'})

url = 'https://www.youtube.com/watch?v=d95PPykB2vE'
video_info = ydlp.extract_info(url, download=False)

# 筛选目标格式
target_format = next(f for f in video_info['formats'] 
                    if f['height'] == 720 and f['vcodec'] != 'none' and f['acodec'] == 'none' and f['ext'] == 'webm')

# 为视频信息字典添加请求格式标记
video_info['requested_formats'] = [target_format]
video_info['format_id'] = target_format['format_id']

# 执行下载
ydlp.process_ie_result(video_info, download=True)

关键说明

  • 筛选格式时,vcodec != 'none'表示包含视频流,acodec == 'none'表示无音频流,可根据需求调整筛选条件
  • outtmpl支持多种占位符,比如%(title)s对应视频标题,%(ext)s对应文件扩展名,可灵活自定义输出规则

内容的提问来源于stack exchange,提问作者rangarajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:40:28