Social Media Scraper

Python transcript project

How to Build a YouTube Transcript Extractor with Python

Pass a public YouTube URL to a small standard-library Python script with your Social Media Scraper API key to fetch available caption text and save TXT and JSON files for notes, search, or retrieval.

Illustration showing a code editor, a public YouTube video input, and plain text and JSON output files without timestamps
Illustration of a Python transcript workflow from video URL to TXT and JSON files

What Does a Basic Transcript Extractor Do?

A small Python script takes one public YouTube URL, calls youtube.transcript via the YouTube transcript API, and writes a UTF-8 TXT file plus a JSON file. It uses Python standard-library modules with an API key and funded account balance.

One video URL per request

Pass one public YouTube URL on the command line. Check documented optional parameters before adding extra query fields.

Plain TXT and JSON files

Write available caption text to a UTF-8 TXT file and save the returned data object in a JSON file.

API key and account balance

Set SOCIALSCRAPER_API_KEY for the x-api-key header on a funded account, or test up to three shared anonymous lookups per network per UTC day in the browser tool.

Why Start With a Small Python Script?

Starting with a compact Python script lets you check real caption output on one video before wiring up databases, queues, or search pipelines. You spot missing captions, unexpected field shapes, and HTTP errors early without adding framework overhead.

Check real fields early

Inspect returned fields on one video first so downstream parsers match what the endpoint sends.

Spot request errors quickly

A focused script shows HTTP status codes and empty caption responses clearly without extra framework layers.

Keep setup lightweight

Standard-library HTTP and JSON modules keep setup simple while you verify the extraction flow.

How Do You Fetch and Save a Transcript in Python?

Download the Python script, export SOCIALSCRAPER_API_KEY in your terminal, and run it with a public YouTube URL and an --out path. After the request finishes, open the TXT file to read the text and open the JSON file to inspect the response fields.

  1. Video URL and key
  2. GET youtube.transcript
  3. TXT and JSON files
Workflow diagram from a public video URL and API key to a youtube.transcript GET request and local TXT and JSON files

Export the API key locally

Set SOCIALSCRAPER_API_KEY in your shell environment for x-api-key, and keep keys out of URLs and chat prompts.

Run with URL and --out

Run the script with a target YouTube URL and an --out prefix to save matching TXT and JSON files.

Inspect TXT and JSON files

Open the TXT file for plain caption text and check the JSON file to see the returned fields.

How do you run the Python transcript script?

Run the script from a terminal with SOCIALSCRAPER_API_KEY in your environment, a public YouTube URL, and --out to write UTF-8 TXT and JSON files.

how-to-build-a-youtube-transcript-extractor.py
import argparse
import datetime
import json
import os
import pathlib
import urllib.error
import urllib.parse
import urllib.request
import uuid

ORIGIN = "https://socialmediascraper.org"

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None

def fetch(operation, params):
    key = os.environ.get("SOCIALSCRAPER_API_KEY")
    if not key:
        raise SystemExit("Set SOCIALSCRAPER_API_KEY in your environment first.")
    url = ORIGIN + "/v1/" + operation.replace(".", "/")
    request = urllib.request.Request(url + "?" + urllib.parse.urlencode(params), headers={
        "x-api-key": key,
        "Idempotency-Key": str(uuid.uuid4()),
        "Accept": "application/json",
        "User-Agent": "SocialMediaScraperTutorial/1.0",
    })
    try:
        with urllib.request.build_opener(NoRedirect()).open(request, timeout=40) as response:
            payload = json.load(response)
    except urllib.error.HTTPError as error:
        raise SystemExit("Request stopped with HTTP " + str(error.code)) from None
    except (OSError, ValueError):
        raise SystemExit("Request failed; inspect the saved request status before retrying.") from None
    data = payload.get("data")
    if not isinstance(data, dict):
        raise SystemExit("No data object returned; inspect the API response contract.")
    return data

parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--out", default="research-output")
args = parser.parse_args()
destination = pathlib.Path(args.out)
if destination.exists() or destination.with_suffix(".json").exists():
    raise SystemExit("Output exists. Choose another --out before starting a new billed request.")
destination.parent.mkdir(parents=True, exist_ok=True)

data = fetch("youtube.transcript", {"url": args.input})
text = data.get("text")
if not isinstance(text, str) or not text.strip():
    raise SystemExit("No transcript text was returned for this video.")
destination.with_suffix(".txt").write_text(text, encoding="utf-8")
destination.with_suffix(".json").write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
print(destination.with_suffix(".txt"))

Copy or download the request, Python script, or n8n workflow, then run it in your own environment with an active API key and balance.

What Fields Appear in the Saved Files?

The TXT file holds plain caption text for reading, while the JSON file stores returned fields such as text, language, and source_url. Missing or omitted fields stay null or absent, and timestamps, segments, or speaker labels are not guaranteed.

Plain text in the TXT file

Open the TXT file to verify that caption text is present and saved as UTF-8.

Returned fields in JSON

Inspect text, language, and source_url in the JSON file and handle null or omitted fields.

No guaranteed timing or speakers

Build around plain text and optional metadata, since timestamps, timed segments, and speaker labels are not guaranteed.

Response schema field types and shapes
{
  "text": "string",
  "language": "string | null",
  "source_url": "string | null"
}
Example field schema showing expected field names and types (string, null, or omitted), not a live query result or performance metric.

Who Can Extend This Into Search or Notes?

Researchers organizing video research, teams building search indexes, or builders feeding RAG applications can connect the saved files to their own pipeline after checking one record. Add chunking, embeddings, storage, or scheduling yourself rather than relying on built-in automation.

Video research and notes

Use saved TXT and JSON files to organize video research and searchable notes after checking sample caption output.

Search indexes and RAG workflows

Feed saved text into search indexes or RAG applications after checking chunk boundaries and caption quality on sample videos.

Multi-video runs and schedules

Add a batch loop, queue, or scheduler only after checking single-video outputs and planning request counts.

When Do Captions or Output Files Fail?

Videos without available captions or with access restrictions may return no transcript text, and HTTP errors need explicit handling in your script. The script does not retry failed requests automatically, stops if the target JSON exists, and requires account balance for REST calls.

Missing or restricted captions

Handle missing or empty transcript text in your script when a video lacks captions or restricts access.

Existing output JSON file

Choose a new --out path or remove the existing JSON file before running, because the script stops instead of overwriting it.

Failed requests and balance

Surface HTTP errors directly without automatic retries, and keep your account balance funded for REST requests.

What Questions Come Up Before Running the Script?

Read the API documentation →

How to try the browser tool or review the setup

Test a public YouTube video URL in the free browser tool within the shared daily limit, or review the youtube.transcript parameters and Python script steps.