1. Tutorials
  2. How to scrape YouTube video transcript
  3. Python

How to scrape YouTube video transcript with Python

A Python script that fetches YouTube video transcript and saves them to a file.

Get an API key; the examples use api.socialscrape.dev.

Set up

You need Python 3 and the requests package.

1python -m venv .venv2source .venv/bin/activate3pip install requests4export SOCIALSCRAPE_API_KEY=ss_live_...

The script

Save as scrape.py and run python scrape.py. It calls GET /v1/youtube/video/transcript.

1import json2import os3import time45import requests67URL = "https://api.socialscrape.dev/v1/youtube/video/transcript"8HEADERS = {"x-api-key": os.environ["SOCIALSCRAPE_API_KEY"]}9PARAMS = {10    "id": "dQw4w9WgXcQ",11    "language": "de",12}131415def pick(obj, *path):16    """Follow a path through nested dicts; None if any step is missing or null."""17    for key in path:18        obj = obj.get(key) if isinstance(obj, dict) else None19    return obj202122def get(params):23    """One request. Failures cost nothing; retry the ones the API marks retryable."""24    for attempt in range(3):25        body = requests.get(URL, headers=HEADERS, params=params, timeout=60).json()26        if body["ok"]:27            return body28        err = body["error"]29        if not err["retryable"] or attempt == 2:30            raise RuntimeError(f'{err["code"]}: {err["message"]}')31        time.sleep(2**attempt)323334body = get(PARAMS)35data = body["data"]3637with open("out.json", "w", encoding="utf-8") as f:38    json.dump(data, f, ensure_ascii=False, indent=2)3940print("text:", str(pick(data, "text"))[:200])41print(f"saved out.json, credits left: {body['credits_remaining']}")

How it works

  1. get() sends one request and retries the failures the API marks retryable. A failed request costs nothing.
  2. The result is one object in data.
  3. pick() reads nested fields and gives None instead of crashing when the platform returned null.
  4. The whole object goes to out.json and a few fields are printed.

What you get back

These fields come from a recorded sample. The full field list is on the endpoint page.

SampleFields in the script
1{2  "text": "Uns beiden ist die Liebe nicht fremd Du kennst die Regeln genau wie ich Für mich zählst nur du Das kriegst du sonst von keinem hier Ich will dir sagen, wie i..."3}

The short version

Without paging, saving or retries, the request is this.

1import os2import requests34params = {5    "id": "dQw4w9WgXcQ",6    "language": "de",7}8res = requests.get(9    "https://api.socialscrape.dev/v1/youtube/video/transcript",10    headers={"x-api-key": os.environ["SOCIALSCRAPE_API_KEY"]},11    params=params,12    timeout=60,13)14body = res.json()1516if body["ok"]:17    print(body["data"])18else:19    print(body["error"]["code"], body["error"]["message"])

With the SDK

The Python client does the retries for you: see the SDKs.

1from socialscrape import SocialScrape23client = SocialScrape()  # reads SOCIALSCRAPE_API_KEY45res = client.youtube.video_transcript(id="dQw4w9WgXcQ", language="de")6print(res.data)7print(res.credits_charged, res.credits_remaining)

What it costs

1 credit for captions; AI transcription 1 up to 2 minutes, then 5 per started minute of the whole video. A failed request costs nothing. Add max_age_days to reuse a cached result for 0 credits. Results are kept 30 days.

Next