DEV Community

Cover image for How to Extract YouTube Transcripts with Python and Olostep
Bala Priya C
Bala Priya C

Posted on Edited on

How to Extract YouTube Transcripts with Python and Olostep

A transcript is the full text of what a speaker says in a video. You can search it, quote it, or feed it to a summarizer.

To get one in Python on your own, the script usually has to do these jobs:

  • Identify the video from its link. Watch, youtu.be, Shorts and embed links all have different formats.
  • Get the video's caption data from YouTube.
  • Parse the captions into lines with offsets.
  • Handle failures, such as videos with no captions.

Each of these jobs is code you write, test and maintain. I recently came across Olostep's YouTube transcript generator, and it reduces the steps one API call. You send the video link with the @olostep/youtube-transcript parser and get back JSON: the channel, the language, and every line with its offset. Olostep handles the page request, the caption lookup and the parsing on its side. Your code makes one call, and error handling shrinks to a short try/except.

In this tutorial, you'll learn how to fetch a YouTube transcript with Python. You'll build the script one step at a time: set up your API key, send one request to the Olostep Scrapes API, and print each line with its timestamp.

Let's get started!

Prerequisites

  • Python 3.11 - 3.13 (the olostep SDK requires it)
  • The SDK: pip install olostep
  • An Olostep API key. New accounts get 500 free credits. Sign up at olostep.com/auth.

What You Are Calling

Olostep's Scrapes API takes a URL and returns its content. For YouTube links, the built-in @olostep/youtube-transcript parser returns structured JSON: the channel, the language, and a list of text segments with offsets.

The parser reads a video's existing captions, auto-generated ones included. It does not run speech-to-text on the audio, so a video with no captions has nothing to fetch.

It accepts any single-video link: youtube.com/watch, youtu.be, Shorts, live and embed links, and the like. Playlists and channels are not supported. Each transcript uses 3 credits, and failed requests are not charged, per the Olostep tool page.

Step 1: Load Your API Key

Create a file called get_youtube_transcript.py. The first job is getting your key into the script without pasting it into the source.

import os
from getpass import getpass

# 1. Retrieve the API key
api_key = os.getenv("OLOSTEP_API_KEY")
if not api_key:
    api_key = getpass("Please enter your Olostep API Key: ")
    os.environ["OLOSTEP_API_KEY"] = api_key
Enter fullscreen mode Exit fullscreen mode

Let's parse it:

  • os.getenv looks for an OLOSTEP_API_KEY environment variable.
  • If it is empty, getpass prompts you and hides what you type.
  • The last line saves the key for the rest of the session, so you type it once.

Your key never lands in the source file, so you can commit the script without leaking it.

Step 2: Create the Client

Next, import the SDK and create a client. Every API call goes through this object.

from olostep import Olostep  # make sure you've installed the Python SDK

# 2. Initialize the client
client = Olostep(api_key=api_key)
Enter fullscreen mode Exit fullscreen mode

Nothing runs against the API yet. This step only builds the client.

Step 3: Request the Transcript

Now the actual call. Add your video link and send it to the Scrapes API with the YouTube parser. I've tried to get the transcript for this Real Python video on timer functions.


VIDEO_URL = "https://www.youtube.com/watch?v=YOUR_VIDEO_ID"  # paste your video link here

# 3. Get the transcript
result = client.scrapes.create(
    url_to_scrape=VIDEO_URL,
    formats=["json"],
    parser="@olostep/youtube-transcript",
)
Enter fullscreen mode Exit fullscreen mode

The following three arguments do the work:

  • url_to_scrape is the video link.
  • formats=["json"] asks for structured output. The parser only applies when json is a requested format.
  • parser picks the YouTube transcript parser.

The parsed transcript comes back in result.json_content as a Python dictionary. The next step reads it.

Step 4: Read the Transcript Data

result.json_content already holds a dictionary, so you assign it to data and index into it. No extra parsing step is needed.

data = result.json_content
print(data["channel"], data["language"])
Enter fullscreen mode Exit fullscreen mode

You should see an output like so:

{'id': 'UCI0vQvr9aFn27yR6Ej6n5UA', 'name': 'Real Python'} en
Enter fullscreen mode Exit fullscreen mode

Your channel and language will differ. The transcript itself sits in data["segments"], which is a list. Each item has the spoken text and an offset.

Step 5: Print Each Line with Its Timestamp

Loop over the segments and print them.

for segment in data["segments"]:
    print(f"{segment['offset']:.0f}s  {segment['text']}")
Enter fullscreen mode Exit fullscreen mode

Here's the truncated output:

0s  Here is a little riddle for you. The
2s  older you get, the less you have of it.
4s  What is it? The correct answer is money.
7s  I mean, time. The older you get, the
10s  less time you have available. So, I
12s  guess it's a good idea to be aware of
14s  time. And as usual, Python is great at
17s  helping us with that. Besides other
19s  handy modules and packages, Python
21s  standard library also contains the time
24s  module. That means the only line of code
26s  that you need to work with time in
28s  Python is import time. And once time is
32s  present, you can do a bunch of cool
...
335s  >> We'll look at an initial timer class.
337s  Then we'll look at what multiple timers
339s  would look like. We'll then be enhancing
340s  our timer class to work as a data class.
343s  We'll explore context managers as well
345s  as looking at how our timer class could
347s  be made into a context manager and then
349s  seeing it in action. So if you value
352s  time as much as I do, check out the
354s  video course by Marti. I've linked it
356s  here somewhere and of course in
358s  description below.
Enter fullscreen mode Exit fullscreen mode

Image descr

For one block of plain text, swap the loop for a join:

print(" ".join(segment["text"] for segment in data["segments"]))
Enter fullscreen mode Exit fullscreen mode

To save it, write that string to a file with open("transcript.txt", "w").

Step 6: Handle Videos With No Transcript

But what happens when a video has no captions? The request fails, and the script stops with a traceback. Captions turned off, a private or removed video, and age restrictions all produce this case.

Wrap steps 3 to 5 in a try/except block:

try:
    ...  # steps 3 to 5 go here, indented one level
except Exception as e:
    print(f"An error occurred while fetching the transcript: {e}")
Enter fullscreen mode Exit fullscreen mode

Now a failed video prints its error message and the script ends cleanly. Failed requests are not charged, so you can run this over a list of videos without paying for the misses. For a list, put the block inside a for url in urls: loop. The parser takes one video per call.

Your get_youtube_transcript.py should now look like so. Replace YOUR_VIDEO_ID with the video you need the transcript for and run it with python get_youtube_transcript.py.

Next Steps

You now have a script that turns a YouTube link into timestamped text. From here, you can feed the transcript into a summarizer, index it for search, or draft a blog post from a talk you gave.

You can also give the YouTube transcript generator a try here:

Paste a YouTube link and get the full transcript in seconds. Copy it, download it as .txt, or show timestamps. Works with Shorts and live videos.

olostep.com

References:


Note: Cover image generated with the built-in image generation feature on dev.to.

Top comments (1)

Collapse
 
alexshev profile image
Alex Shev •

A transcript pipeline becomes much more dependable when it preserves provenance beside the text: source URL, retrieval time, language, speaker/timestamp availability, and the extraction method. That lets downstream summarization or search distinguish a clean caption track from a fallback transcript instead of treating every string as equally reliable.