如何使用 youtube-dl 下载英文 YouTube 视频字幕?

How to download YouTube video subtitles in English using youtube-dl?

我尝试使用以下 Python 3.x 代码将字幕与视频一起下载。就是不行。

这是我的代码:

from __future__ import unicode_literals
import youtube_dl
ydl_opts = {
'outtmpl': '/PATH/%(title)s'+'.mp4',
'format':' (bestvideo[width>=?1080]/bestvideo)+bestaudio/best',
'subtitle': '--write-srt --sub-lang en',
}
url = input("Enter your URL: ")
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([url])
print("Downloaded!")

您需要为 youtube-dl 设置 'writesubtitles': True 才能下载字幕。另外,您应该指定 [ext=mp4] 否则程序可能会下载与 mp4 格式不兼容的 .webm 文件。下面的代码解决了这些问题:

from __future__ import unicode_literals
import youtube_dl
ydl_opts = {
'outtmpl': '/Downloads/%(title)s_%(ext)s.mp4',
'format': '(bestvideo[width>=1080][ext=mp4]/bestvideo)+bestaudio/best',
'writesubtitles': True,
'subtitle': '--write-sub --sub-lang en',
}
url = input("Enter your URL: ")
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([url])
print("Download Successful!")

此外,请务必将 ffmpeg.exe 保存在您的 youtube-dl 文件夹中,以便合并视频和音频文件。你可以得到它 from here.