python-3.xyt-dlp

How can get the subtitle with yt-dlt's python script?


Install yt-dip to work:

pip install  yt-dlp  

Get the subtitle in youtube with bash command:

url="https://www.youtube.com/watch?v=ZrQJaLemaoE"
yt-dlp  --write-auto-sub  --sub-lang en --skip-download  $url --output  /tmp/sub.txt

How can get the substitle with pure python script?

import yt_dlp
url="https://www.youtube.com/watch?v=ZrQJaLemaoE"
ydl_opts = {
     "write_auto_sub":True,
     "sub_lang":'en',
     "skip_download":True,
     "output":'/tmp/sub.txt',
    }
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    ydl.download(url)

It can't download substitute with pure python code,how to fix it?


Solution

  • import yt_dlp
    
    url = "https://www.youtube.com/watch?v=ZrQJaLemaoE"
    
    ydl_opts = {
      'writeautomaticsub': True,
      'subtitlesformat': 'srt',
      'skip_download': True,
      'outtmpl': '/tmp/sub.srt' 
    }
    
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
      ydl.download([url])
    

    The key options are:

    writeautomaticsub: Download automatic subtitles

    subtitlesformat: Format of subtitles to download (srt, ass, etc)

    skip_download: Only download subtitles, not video

    outtmpl: Output filename template for subtitles

    This will download the best available subtitles for the video to the specified file.