yt-dlp下载错误:用Python下载特定的YouTube视频时,请求的格式不可用
我在macOS的 Python 3.13虚拟环境中使用yt-dlp下载视频。但是,对于一个特定的视频(QageNN-V8rY),下载因DownloadError失败。
File "/Users/ashazakhtar/coding/project-idea/.venv/lib/python3.13/site-packages/yt_dlp/YoutubeDL.py", line 1093, in trouble
raise DownloadError(message, exc_info)
yt_dlp.utils.DownloadError: ERROR: [youtube] QageNN-V8rY: Requested format is not available. Use --list-formats for a list of available formats
我的当前代码:
def transcript_video(self, url):
with tempfile.TemporaryDirectory() as temp_dir:
output_path = os.path.join(temp_dir, "audio.m4a")
cookie_path = os.path.join(settings.BASE_DIR, "www.youtube.com_cookies.txt")
ydl_opts = {
"format": "bestaudio[ext=m4a]/bestaudio[ext=webm]/bestaudio",
"quiet": True,
"outtmpl": output_path,
"cookiefile": cookie_path,
"nocheckcertificate": True,
"user_agent": "Mozilla/5.0",
"cookies_readonly": True,
}
with YoutubeDL(ydl_opts) as ydl: # type: ignore
ydl.download([url]) # type: ignore
print(f"Audio file size: {os.path.getsize(output_path)} bytes")
# Send audio file to local FastAPI
with open(output_path, "rb") as audio_file:
response = requests.post(
f"{FASTAPI_BASE_URL}/transcribe",
files={"file": ("audio.m4a", audio_file, "audio/m4a")},
timeout=300, # whisper can be slow on CPU
)
response.raise_for_status()
result = response.json()
print(f"Transcription done: {result['text'][:100]}...")
return result["text"]
我尝试过的办法:
- 我已在浏览器中确认视频URL正确且可访问。
- 我在虚拟环境中将yt-dlp更新到了最新版本(pip install -U yt-dlp)。
- 通过命令行运行yt-dlp --list-formats https://www.youtube.com/watch?v=QageNN-V8rY 可以看到可用的格式,但我的Python脚本仍然因格式错误而失败。
如何配置我的ydl_opts字典,使其能够动态选择该视频的“可用中最优格式”,从而避免抛出缺少格式的异常?
解决方案
使用不依赖扩展名的更健壮的选择器:
ydl_opts = {
"format": "bestaudio/best",
"quiet": True,
"outtmpl": output_path,
"cookiefile": cookie_path,
"nocheckcertificate": True,
"user_agent": "Mozilla/5.0",
"cookies_readonly": True,
}
如果你需要m4a以保持Whisper的一致性,请不要过滤格式——改为转换格式:
ydl_opts = {
"format": "bestaudio/best",
"outtmpl": output_path,
"quiet": True,
"cookiefile": cookie_path,
"postprocessors": [{
"key": "FFmpegExtractAudio",
"preferredcodec": "m4a",
}],
}
给你的小贴士:运行这段Python代码,看看yt-dlp实际看到的是什么:
with YoutubeDL({"listformats": True}) as ydl:
ydl.download([url])
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。