# YouTube Transcript Scraper (`shanks0x0/youtube-transcript-scraper`) Actor

Extracts full transcripts and metadata from YouTube videos. Supports single videos, channels, and playlists — returns timestamped segments, plain text, SRT, or VTT with video title, channel name, duration, and language info. No API key or proxy needed.

- **URL**: https://apify.com/shanks0x0/youtube-transcript-scraper.md
- **Developed by:** [Meherab Hossain](https://apify.com/shanks0x0) (community)
- **Categories:** Videos, Social media, Developer tools
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $4.00 / 1,000 results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## YouTube Transcript Scraper

An Apify Actor that extracts transcripts (captions/subtitles) from YouTube videos, channels, and playlists. It tries the lightweight YouTube Innertube/timedtext API first (HTTP-only, no browser), and falls back to Playwright headless browser when the API path fails.

**Pricing:** $0.01 per successfully extracted transcript (Pay-Per-Event).

### Features

- **Video, channel, and playlist support** — paste any YouTube URL
- **Timed segments** — each transcript comes with start time, duration, and text
- **Multiple output formats** — segments (default), plain text, SRT, VTT
- **Language preferences** — specify preferred languages in order
- **Translation** — fetch transcripts translated into another language via YouTube's `tlang` parameter
- **Auto-generated captions** — optionally include or exclude ASR captions
- **Smart proxy strategy** — starts without proxy, switches to residential proxy after 3 consecutive IP blocks
- **Browser fallback** — Playwright Chromium used when the HTTP API path fails
- **PPE pricing** — only charged on success, no charge for failures

### Input

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `source` | string | yes | — | YouTube video/channel/playlist URL or bare ID |
| `sourceType` | enum | no | `auto` | Force source interpretation: `auto`, `video`, `channel`, `playlist` |
| `maxVideos` | integer | no | 50 | Max videos for channels/playlists (0 = unlimited, capped at 500) |
| `languages` | string\[] | no | `[]` | Ordered language preference (e.g. `["en", "es"]`) |
| `translateTo` | string | no | `""` | Translation target language code (e.g. `"es"`) |
| `format` | enum | no | `segments` | Output format: `segments`, `plain`, `srt`, `vtt` |
| `includeAutoGenerated` | boolean | no | `true` | Include ASR captions |
| `useProxy` | enum | no | `auto` | Proxy strategy: `auto`, `always`, `never` |
| `useBrowserFallback` | boolean | no | `true` | Enable Playwright fallback |

#### Example input

```json
{
    "source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "languages": ["en"],
    "format": "segments"
}
```

### Output

Each result is a JSON object with:

| Field | Type | Description |
|---|---|---|
| `videoId` | string | 11-char YouTube video ID |
| `videoUrl` | string | Full watch URL |
| `title` | string | Video title |
| `channelName` | string | Channel/uploader name |
| `channelId` | string | Channel ID (UC...) |
| `publishedAt` | string | ISO 8601 publish date |
| `durationSeconds` | integer | Video duration in seconds |
| `language` | string | Language code of the fetched caption track |
| `isAutoGenerated` | boolean | True if ASR captions |
| `isTranslated` | boolean | True if a translation was fetched |
| `transcript` | string | Full transcript text (for `plain`/`srt`/`vtt` formats; empty for `segments`) |
| `segments` | array | Timed segments: `{start, duration, text}` (for `segments` format) |
| `extractionMethod` | string | `innertube_api`, `playwright`, or `failed` |
| `error` | string | Error message if extraction failed |

#### Example output

```json
{
    "videoId": "dQw4w9WgXcQ",
    "videoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "title": "Rick Astley - Never Gonna Give You Up (Official Video)",
    "channelName": "Rick Astley",
    "language": "en",
    "isAutoGenerated": false,
    "isTranslated": false,
    "transcript": "",
    "segments": [
        {"start": 0.0, "duration": 4.5, "text": "We're no strangers to love"},
        {"start": 4.5, "duration": 3.2, "text": "You know the rules and so do I"}
    ],
    "extractionMethod": "innertube_api",
    "error": ""
}
```

### Architecture

```
Actor.main()
  │
  ├─ 1. Parse & validate input
  ├─ 2. Resolve source → list of video IDs
  │    ├─ video URL → [1 video ID]
  │    ├─ channel URL → scrape /videos → N video IDs
  │    └─ playlist URL → scrape playlist → N video IDs
  ├─ 3. For each video ID:
  │    ├─ TRY: Innertube API (HTTP-only)
  │    │    ├─ Fetch watch page HTML
  │    │    ├─ Extract ytInitialPlayerResponse
  │    │    ├─ Parse captionTracks
  │    │    ├─ Select best track (language pref)
  │    │    └─ GET baseUrl → parse JSON3 → segments
  │    ├─ IF API FAILS & browser fallback enabled:
  │    │    └─ TRY: Playwright headless browser
  │    └─ IF BOTH FAIL: output with extractionMethod=failed
  ├─ 4. Push results to dataset
  └─ 5. Charge $0.01 per successful transcript (PPE)
```

### Proxy Strategy

| `useProxy` | Behavior |
|---|---|
| `auto` (default) | Start with direct requests. If 3 consecutive IP-block errors (403/429), switch to Apify residential proxy. |
| `always` | Use Apify residential proxy from the start. |
| `never` | Never use proxy. If IP is blocked, the video fails (browser fallback still tried without proxy). |

### Local Development

#### Install dependencies

```bash
pip install -r requirements.txt
playwright install --with-deps chromium
```

#### Run locally

```bash
## Single video
python -m src.main dQw4w9WgXcQ

## With JSON input
echo '{"source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "format": "plain"}' | python -m src.main

## Run tests
pytest tests/ -v
```

#### Building for Apify

```bash
apify push
```

### Cost Estimation

| Scenario | Videos | Success rate | Cost |
|---|---|---|---|
| Single video | 1 | 95% | ~$0.01 |
| Channel (50 videos) | 50 | 80% | ~$0.40 |
| Playlist (100 videos) | 100 | 85% | ~$0.85 |

### Tech Stack

- **Language:** Python 3.12+
- **SDK:** Apify SDK for Python (v2.x)
- **HTTP client:** httpx
- **Browser:** Playwright (Chromium) — fallback only
- **Base image:** `apify/actor-python:3.12`

# Actor input Schema

## `source` (type: `string`):

YouTube video URL, channel URL, or playlist URL. Also accepts bare video IDs (11 chars) or channel IDs (UC...).

## `sourceType` (type: `string`):

Force the interpretation of the source URL. 'auto' detects from the URL pattern.

## `maxVideos` (type: `integer`):

Maximum number of videos to process (for channels and playlists). Set 0 for unlimited (capped at 500). Ignored for single video sources.

## `languages` (type: `array`):

Ordered list of language codes to try (e.g. \['en', 'en-US', 'es']). The first available track matching is used. Empty = accept any language.

## `translateTo` (type: `string`):

If set, fetch a translation of the transcript into this language code (e.g. 'es'). Uses YouTube's tlang parameter. Empty = no translation.

## `format` (type: `string`):

How to structure the transcript text in the output.

## `includeAutoGenerated` (type: `boolean`):

If true, include auto-generated (ASR) captions when no manual captions exist. If false, only manual/human-authored captions are returned.

## `useProxy` (type: `string`):

Force proxy usage. 'auto' tries without proxy first, then uses Apify Proxy on failure. 'always' always uses Apify Proxy. 'never' never uses a proxy.

## `useBrowserFallback` (type: `boolean`):

If true, fall back to Playwright headless browser when the HTTP API path fails for a video. If false, skip browser entirely (faster but lower success rate).

## Actor input object example

```json
{
  "source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  "sourceType": "auto",
  "maxVideos": 50,
  "languages": [
    "en"
  ],
  "translateTo": "",
  "format": "segments",
  "includeAutoGenerated": true,
  "useProxy": "auto",
  "useBrowserFallback": true
}
```

# Actor output Schema

## `results` (type: `string`):

Extracted transcript data stored in the default dataset

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "maxVideos": 50,
    "languages": [
        "en"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("shanks0x0/youtube-transcript-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "maxVideos": 50,
    "languages": ["en"],
}

# Run the Actor and wait for it to finish
run = client.actor("shanks0x0/youtube-transcript-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "source": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  "maxVideos": 50,
  "languages": [
    "en"
  ]
}' |
apify call shanks0x0/youtube-transcript-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=shanks0x0/youtube-transcript-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/Q82ck2DqR9DFuCtgH/builds/QeOkgQHWhSsAR2hwb/openapi.json
