The Wayback Machine - https://web.archive.org/web/20241010025828/https://www.geeksforgeeks.org/python-downloading-captions-from-youtube/
Open In App

Python – Downloading captions from YouTube

Last Updated : 06 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Transcript API is very simple to use provides various features.

In this article, we will learn how to download captions or subtitles from a YouTube video. The subtitles can be auto-generated by YouTube or can be manually added by the mentor, in case it has both types available we would take a look at how to get specifically manual or automatic captions too. We would also explore how to get captions of specific languages and translate captions from one language to another. Then we would also see how to write the transcript in a text file.

youtube_transcript_api: This module is used for getting the captions/subtitles from a YouTube Video. It can be installed using:

pip install youtube-transcript-api # for windows
or 
pip3 install youtube-transcript-api # for Linux and MacOs 

Before starting with the process we would like to explain how we can get the video id of a YouTube video. For Example, if a YouTube video has the following URL

https://youtu.be/SW14tOda_kI

Then the video id for this video would be “SW14tOda_kI”, i.e. all the phrases after the ?v= counts as the video id. This is unique for each video on YouTube.

Getting Started

  • Now we would start with the basics, In the first code snippet, we are trying to get the transcript of the video id using the .get_transcript() function.
  • It returns us a list of dictionaries in which each dictionary contains 3 key-value pair inside it, the first one being the content, the second one being the time instant from which the caption sentence/phrase start to be spoken and the third one being the duration in seconds that is taken to speak the sentence or phrase completely.
  • First-line basically imports the required packages and the next line assigns a variable to store the list of dictionaries and finally on the 3rd line it prints out the variable.

Python3




from youtube_transcript_api import YouTubeTranscriptApi
  
# assigning srt variable with the list
# of dictionaries obtained by the get_transcript() function
srt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI")
  
# prints the result
print(srt)


 
 

Output:

 

 

For getting transcripts of more than one video we can pass them using commas, as in YouTubeTranscriptApi.get_transcript(videoid1, Videoid2, ….), in this case, we would have a list of lists and gain inside each inner list we would have a dictionary.

 

Getting Transcript of a particular Language

 

Now if we want to get the transcript of a specific language, we can mention the language as a parameter. In the next code snippet, we aim to do the same. All the code and working would be the same as the previous example with the difference that this time it will get only the transcripts in English and ignore subtitles if any exists. 

 

Python3




from youtube_transcript_api import YouTubeTranscriptApi
 
# assigning srt variable with the list of dictionaries
# obtained by the .get_transcript() function
# and this time it gets only the subtitles that
# are of english language.
srt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI",
                                          languages=['en'])
 
# prints the result
print(srt)


Output:

Since the video we are considering for this example, only has English subtitles so both the examples gave us the same answer. 

Getting List of all transcripts

  • Now to get the list of all transcripts of a video we can use the .list_transcripts() function. This function returns us all the transcripts of all the languages available for the video. It returns the TranscriptList object which is iterable and provides methods to filter the list of transcripts for specific languages and types.
  • Next, we use functions to fetch some data about the transcript from the metadata obtained.
    • transcript.video_id returns us the video ID of the video
    • transcript.language returns us the language of the transcript
    • transcript.language_code returns us the language code of the transcript, for example, “en” for English, etc.
    • transcript.is_generated tell us whether it has been manually created or generated by YouTube
    • transcript.is_translatable tells whether this transcript can be translated or not
    • transcript.translation_languages which give us a list of languages the transcript can be translated to.
  • Then we use .fetch() function to fetch the actual transcript.
  • Then we also showed how to use the .translate() function to convert/translate the caption from one language to another if at all it’s translatable (since we have only English subtitles for this language it might be not evident in this case, but this translation is very useful if there are transcripts of more than one language in the video).
  • Next line we have the .find_transcript() function that helps us to get the actual transcript of the video we are wanting along with the metadata.
  • Finally, we used the .find_manually_created_transcript() function to specifically find manual subscripts, similar to this we have .find_generated_transcript() which we have not used in this example since there are no generated captions, and we have only manual captions here.

Python3




# importing the module
from youtube_transcript_api import YouTubeTranscriptApi
 
# retrieve the available transcripts
transcript_list = YouTubeTranscriptApi.list_transcripts('SW14tOda_kI')
 
# iterate over all available transcripts
for transcript in transcript_list:
 
    # the Transcript object provides metadata
    # properties
    print(
        transcript.video_id,
        transcript.language,
        transcript.language_code,
       
        # whether it has been manually created or
        # generated by YouTube
        transcript.is_generated,
         
        # whether this transcript can be translated
        # or not
        transcript.is_translatable,
         
        # a list of languages the transcript can be
        # translated to
        transcript.translation_languages,
    )
 
    # fetch the actual transcript data
    print(transcript.fetch())
 
    # translating the transcript will return another
    # transcript object
    print(transcript.translate('en').fetch())
 
# you can also directly filter for the language you are
# looking for, using the transcript list
transcript = transcript_list.find_transcript(['en'])
 
# or just filter for manually created transcripts
transcript = transcript_list.find_manually_created_transcript(['en'])


Output:

Writing Subtitles to Text File

Now we would see how can we can write subtitles of a YouTube video in a text file. For that first, we would import the modules and then get the transcript or caption using the .get_transcript() function and store it into a variable. Then we would use the built-in file reader of python. The line uses a context manager so that we need not worry to close the file after our work is done. We open a file named subtitles.txt in write mode and then inside it we would iterate through each element of the list and then write it to the file. The code is as follows:

Python3




# importing modules
from youtube_transcript_api import YouTubeTranscriptApi
 
# using the srt variable with the list of dictionaries
# obtained by the .get_transcript() function
srt = YouTubeTranscriptApi.get_transcript("SW14tOda_kI")
 
# creating or overwriting a file "subtitles.txt" with
# the info inside the context manager
with open("subtitles.txt", "w") as f:
   
        # iterating through each element of list srt
    for i in srt:
        # writing each element of srt on a new line
        f.write("{}\n".format(i))


Output:

The file would be created in the same directory as that of the .py file if you just enter the name of the file in the context manager, to create/save it at a different location we need to give it’s absolute or relative path. Also, the program can generate error for unknown characters in the caption. However, the subtitle file will be created with known characters.



Similar Reads

How to download public YouTube captions in XML using Pytube in Python?
Prerequisite: Pytube Pytube is a dependency-free lightweight Python library for downloading YouTube videos. There are various APIs to fetch metadata from YouTube. In this article, we are going to see how to download public YouTube captions in XML using Python. Before starting we need to install this module: pip install pytube Approach: Import pytub
2 min read
Create GUI for Downloading Youtube Video using Python
Prerequisites: Python GUI – tkinter YouTube is a very popular video-sharing website. Downloading a video's/playlist from YouTube is a tedious task. Downloading that video through Downloader or trying to download it from a random website increase's the risk of licking your personal data. Using the Python Tkinter package, this task is very simple-eff
12 min read
How to Extract YouTube Comments Using Youtube API - Python
Prerequisite: YouTube API Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video et
2 min read
GUI to get views, likes, and title of a YouTube video using YouTube API in Python
Prerequisite: YouTube API, Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this art
2 min read
Downloading PDFs with Python using Requests and BeautifulSoup
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object. Requests library i
2 min read
Downloading files from web using Python
Requests is a versatile HTTP library in python with various applications. One of its applications is to download a file from web using the file URL. Installation: First of all, you would need to download the requests library. You can directly install it using pip by typing following command: pip install requests Or download it directly from here an
4 min read
Pafy - Downloading Stream
In this article we will see how we can download given youtube video stream in pafy. Pafy is a python library to download YouTube content and retrieve metadata. Pafy object is the object which contains all the information about the given video. Stream is basically available resolution of video is available on youtube. Downloaded file get saved in th
2 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uploaded and displaying the file name on the screen ap
7 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
YouTube Media/Audio Download using Python - pafy
This tutorial will help you download youtube video or audio with python using pafy library. Pafy library is used to retrieve YouTube content and metadata. Features of Pafy (i) Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords. (ii) Download video or audio at requested resolution / bitrate / format / filesize (iii) C
2 min read
How to extract image information from YouTube Playlist using Python?
Prerequisite: YouTube API Google provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video, et
2 min read
Python | Program to download complete Youtube playlist
Python is a multi-purpose programming language and is widely used for scripting small tasks. Let's see how to make your own Youtube Playlist Downloader using Python. Though there are many software available in the market but making your own serving that purpose is quite a learning and impressive as well. Modules needed: BeautifulSoup bs4PyQt5PyQtWe
3 min read
Python - Obtain title, views and likes of YouTube video using BeautifulSoup
In this article, we will learn how can we obtain data (like title, views, likes, dislikes etc) from any YouTube video using a Python script. For this task, we are going to use very famous library for web scraping BeautifulSoup and Requests. Modules required and Installation : Requests : Requests allows you to send HTTP/1.1 requests extremely easily
2 min read
Playing Youtube Video using Python
In this article, we will see how we can play youtube video in python. In order to play youtube videos in python we need pafy and vlc module. Pafy is a Python library to download YouTube content and retrieve metadata. Below is the command to install pafy pip install pafy VLC : is a python library to use the functionality of the vlc media player. In
2 min read
How to extract youtube data in Python?
Prerequisites: Beautifulsoup YouTube statistics of a YouTube channel can be used for analysis and it can also be extracted using python code. A lot of data like viewCount, subscriberCount, and videoCount can be retrieved. This article discusses 2 ways in which this can be done. Method 1: Using YouTube API First we need to generate an API key. You n
3 min read
Get information about YouTube Channel using Python
Prerequisite: YouTube API Google provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video, et
3 min read
Download Youtube Video(s) or whole Playlist with Python
Prerequisite: Tkinterpyyoutubepytubethreading in TkinterYouTube API Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to cre
6 min read
Automate YouTube Music to Spotify with Python
Sometimes we listen to a song on YouTube music, and we really found that song interesting, and you want to add that to your Spotify playlist. Then you manually search that song, add it to the Spotify playlist. But we can automate that process of searching YouTube songs and add them into Spotify playlist using python programming. In this article, we
7 min read
Automate Youtube with Python
In this article, we are going to see how to automate Youtube using Python. Module usedSelenium: It controlling a web browser through the programpyttsx3: It is a text-to-speech conversion library in Pythonspeech_recognition: Speech Recognition is an important feature in several applications used such as home automation, artificial intelligence, etcp
3 min read
Search and Play Youtube Music with selenium in Python
Automating YouTube Music with Selenium in Python allows you to easily control and manipulate the playback of songs on the platform. This can be a great way to quickly and easily create a personalized listening experience without having to manually navigate through the website. Here, we will see how we can automate YouTube music with selenium in Pyt
6 min read
Pytube | Python library to download youtube videos
YouTube is very popular video sharing website. Downloading a video from YouTube is a tough job. Downloading the Downloader and get the video using that or go to any other website which fetches the video and saves on your computer. Using Python, this task is very easy. Few lines of code will download the video from YouTube for you. For this, there a
4 min read
Extract Video Titles with the Youtube API in Python
Extracting video titles from YouTube can be incredibly useful for various applications, such as data analysis, content creation, and trend tracking. The YouTube Data API provides a robust way to interact with YouTube's platform and extract this information. This guide will walk you through the process of extracting video titles using the YouTube AP
4 min read
Python | Download YouTube videos using yt_dlp module
Each and every day, you must be watching some video or another on YouTube which may be related to Music, Movies, Studies, Research, Leisure etc. You might want to store some video for future use where it will be required due to lack of internet or saving data or any other reason. What if we tell you that you can do this exact very thing using Pytho
1 min read
Youtube Data API for handling videos | Set-1
Before proceeding further let's have a look at what we have in store for the videos section. Youtube Data API allows to perform following operations on the video: list insert update rate getRating reportAbuse delete Let's discuss how to use Youtube Data API for handling videos. Please follow the steps below to enable the API and start using it. Cre
4 min read
Youtube Data API | Set-1
Google provides a large set of API's for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, Youtube Data API is very simple to use provides features like - Search for videosHandle videos like retrieve information about a video, insert a video, delete a video etc.Handle Subscriptions lik
5 min read
Youtube Data API | Set-2
Prerequisite: Youtube Data API | Set-1 In the previous article we have discussed first two variants of search method. Now let's discuss the remaining three- Search Live Events, Search Related Videos and Search My Videos. Search by Live Events: Given example retrieves top 5 live broadcasts associated with the query string Python Programming. type pa
6 min read
Youtube Data API for handling videos | Set-2
Prerequisite: Youtube Data API for handling videos | Set-1 We have recently discussed first two variants of video list method, Video List by Video Id and Video List by Multiple Video Ids. Now, let's discuss the other two variants - Video List Most Popular Videos Video List My Liked Videos List most popular videos: The regionCode parameter states th
6 min read
Youtube Data API for handling videos | Set-3
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2Before proceeding further, first see how to get a list of valid Video Categories, to determine in which category to put a video. For the example we have used the "IN" value for the regionCode parameter. You can use any other value. Only categoryId's that have assignable parameter as v
7 min read
Youtube Data API for handling videos | Set-4
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2, Set-3 In this article we will discuss two methods related to video: Update a Video, Delete a Video. Updating a video and deleting an uploaded video requires user's authorization, so we will be creating OAuth type of credential for this example. Follow the steps below to generate a C
7 min read
Youtube Data API for handling videos | Set-5
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2, Set-3 In this article, we will be discussing Rate a Video and Get Rating of a Video. Examples in this article will be requiring user authorization. So, we will be first creating OAuth Credential and install additional libraries. Follow the steps below to generate a Client Id and a S
5 min read
Article Tags :
Practice Tags :