Python · Tutorial · Transcripts
Build a Research Dataset From Several YouTube Channels: One CSV of Transcripts and Metadata
A Python script that lists the videos of several YouTube channels, fetches each transcript and its stats, and writes one CSV. A real run on three channels, a word-count analysis, the videos that failed, and the credits it cost.
· 7 min read · YTAPI
To build a research dataset from several YouTube channels, list each channel's videos, fetch every transcript and the video's stats, and write one row per video to a CSV with a channel column. The script below does that in about 100 lines of Python. On 2026-11-15 it turned three small sourdough channels into 62 rows, 60 of them with a transcript and 55,845 words of text, in 32 seconds and 126 credits.
We make YTAPI, the API the script calls, so check the numbers against your own run. New accounts get 200 free credits, which is enough for this run.
This post covers the dataset and a first analysis. For feeding a channel to an LLM, see YouTube competitor analysis with AI. For full-text search over one channel's transcripts, see a searchable archive of a YouTube channel.
The CSV schema
One row per video. Every field comes from a YTAPI response.
| Column | Meaning |
|---|---|
channel_id, channel_title | Which channel the video belongs to. |
video_id, url, title | The video. |
published | Publish date, YYYY-MM-DD (UTC), from the Unix timestamp in video info. |
length_seconds | Duration. |
view_count, like_count, comment_count | Stats at the time of the run. Blank when YouTube does not return one (comments turned off, hidden likes). |
status, error_code | ok, or failed with the API's error code. |
language, track_kind | Caption track used. asr is auto-generated, manual is uploaded by the creator. |
word_count | Words in the transcript. |
transcript | The full text on one line. |
Keeping status and error_code in the file means failed videos stay visible in the data instead of silently disappearing, which matters when you later compare channels.
What you need
- Python 3.9 or later with
requests(pip install requests). - A YTAPI key in the
YTAPI_KEYenvironment variable. - Channel handles (
@name) orUC...IDs.
The script
Save this as build_dataset.py.
"""Build one CSV of transcripts and metadata for several YouTube channels.
Usage: YTAPI_KEY=... python build_dataset.py dataset.csv @channel1 @channel2 @channel3
Optional: MAX_VIDEOS=40 limits how many of each channel's newest videos are fetched.
"""
import csv
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import requests
API = "https://api.ytapi.dev"
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['YTAPI_KEY']}"
MAX_VIDEOS = int(os.environ.get("MAX_VIDEOS", "40"))
credits_used = 0 # counted from the X-Credits-Consumed header and the batch totals
COLUMNS = [
"channel_id", "channel_title", "video_id", "url", "title", "published",
"length_seconds", "view_count", "like_count", "comment_count",
"status", "error_code", "language", "track_kind", "word_count", "transcript",
]
def get(path, **params):
"""GET with a short retry on 429 and 5xx. Returns the Response."""
for attempt in range(4):
res = SESSION.get(API + path, params=params, timeout=60)
if res.status_code != 429 and res.status_code < 500:
global credits_used
credits_used += int(res.headers.get("X-Credits-Consumed", 0))
return res
time.sleep(2 * (attempt + 1))
return res
def list_videos(channel):
"""Newest first, up to MAX_VIDEOS. Returns (channel_id, [video dicts])."""
videos, cursor, channel_id = [], None, None
while len(videos) < MAX_VIDEOS:
params = {"sort_by": "newest"}
if cursor:
params["cursor"] = cursor
res = get(f"/v1/channels/{channel}/videos", **params)
res.raise_for_status()
page = res.json()
channel_id = page["channel_id"]
videos += page["videos"]
if not page.get("has_more") or not page.get("next_cursor"):
break
cursor = page["next_cursor"]
return channel_id, videos[:MAX_VIDEOS]
def video_info(video_id):
res = get(f"/v1/videos/{video_id}/video-info")
return res.json() if res.status_code == 200 else None
def fetch_transcripts(video_ids):
"""Batch jobs of up to 100 transcripts. Returns {video_id: result}."""
results = {}
for i in range(0, len(video_ids), 100):
tasks = [{"id": v, "type": "transcript", "video_id": v, "format": "segments"}
for v in video_ids[i:i + 100]]
job = SESSION.post(f"{API}/v1/batch", json={"tasks": tasks, "concurrency": 10}, timeout=60)
job.raise_for_status()
job_id = job.json()["id"]
while True:
time.sleep(2)
status = SESSION.get(f"{API}/v1/batch/{job_id}", timeout=60).json()
if status["status"] in ("completed", "failed"):
break
global credits_used
credits_used += status.get("credits_deducted", 0)
for r in status.get("results", []):
results[r["video_id"]] = r
return results
def main(out_path, channels):
rows = []
for channel in channels:
channel_id, videos = list_videos(channel)
print(f"{channel}: {len(videos)} videos")
for v in videos:
rows.append({"channel_id": channel_id, "video_id": v["video_id"], "title": v["title"]})
with ThreadPoolExecutor(max_workers=4) as pool:
infos = list(pool.map(lambda r: video_info(r["video_id"]), rows))
transcripts = fetch_transcripts([r["video_id"] for r in rows])
with open(out_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=COLUMNS)
writer.writeheader()
for row, info in zip(rows, infos):
info = info or {}
t = transcripts.get(row["video_id"], {})
data = t.get("data") or {}
text = " ".join(s["text"].replace("\n", " ") for s in data.get("segments", []))
published = info.get("published")
writer.writerow({
"channel_id": row["channel_id"],
"channel_title": info.get("channel", {}).get("title", ""),
"video_id": row["video_id"],
"url": f"https://www.youtube.com/watch?v={row['video_id']}",
"title": info.get("title") or row["title"],
"published": datetime.fromtimestamp(published, timezone.utc).date().isoformat() if published else "",
"length_seconds": info.get("length_seconds", ""),
"view_count": info.get("view_count", ""),
"like_count": info.get("like_count", ""),
"comment_count": info.get("comment_count", ""),
"status": "ok" if t.get("status") == 200 else "failed",
"error_code": "" if t.get("status") == 200 else (t.get("error") or {}).get("code", "no_result"),
"language": data.get("language", ""),
"track_kind": data.get("track_kind", ""),
"word_count": len(text.split()),
"transcript": text,
})
ok = sum(1 for r in rows if transcripts.get(r["video_id"], {}).get("status") == 200)
print(f"wrote {len(rows)} rows to {out_path}: {ok} transcripts, {credits_used} credits")
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])Run it with the channels you want:
export YTAPI_KEY=...
python build_dataset.py dataset.csv @SourdoughGeeks @SourdoughSidekick @JoshseasysourdoughMAX_VIDEOS caps how many of each channel's newest videos are taken (40 by default), so a large channel does not spend your credits by accident.
The script makes three kinds of calls:
GET /v1/channels/{id}/videoslists uploads, 30 per page, newest first. 1 credit per page.GET /v1/videos/{id}/video-inforeturns the publish time and the view, like and comment counts. 1 credit per video.POST /v1/batchfetches up to 100 transcripts per job. 1 credit per transcript that succeeds, nothing for failures.
The video-info calls run four at a time. The batch job runs ten transcripts at a time on our side.
The test run
On 2026-11-15 I picked three small public channels by searching YTAPI for "beginner sourdough baking tutorial" and taking channels between 1,000 and 6,000 subscribers: Sourdough Geeks, Sourdough Sidekick and Josh's Easy Sourdough. I picked them for being small, so none of their videos were likely to be cached anywhere.
| Channel | Videos in the run | Transcripts | Words | Words per video | Median length | Median views |
|---|---|---|---|---|---|---|
| Sourdough Geeks | 7 (all uploads) | 5 | 11,089 | 2,217 | 13 min | 350 |
| Sourdough Sidekick | 15 (all uploads) | 15 | 14,844 | 989 | 4 min 26 s | 1,937 |
| Josh's Easy Sourdough | 40 (newest 40, the channel has more) | 40 | 29,912 | 747 | 7 min 8 s | 304 |
| Total | 62 | 60 | 55,845 | 931 |
The first run took 31.8 seconds from the first request to the finished CSV. It spent 126 credits: 4 list pages, 62 video-info calls and 60 transcripts. Failed transcripts were not charged. The CSV is 295 KB.
Publish dates in the file run from 2020-04-16 to 2026-11-05. Of the 62 rows, 6 have no comment_count and 1 has no like_count; I did not check whether those videos have comments turned off.
What failed
Two videos, both on Sourdough Geeks, came back as failed with the error code captions_disabled:
- "Basic Sourdough Loaf - Perfect for Beginners" (2021, 21 minutes)
- "Let's Make Dough: My Stone-Milled Sourdough Bakewell Galette" (2024, 4 minutes)
The channel owner switched captions off on them, so no transcript exists to fetch, and retrying gives the same result. They stayed in the CSV with their stats and an empty transcript. Free basic info shows a video's caption tracks before you spend a credit on its transcript, if you want to skip those videos up front.
Two things the run did not hit, so I cannot show real rows for them:
- Age-restricted, members-only, private and unreleased videos cannot be fetched either. The dashboard's channel export records these in a
reasoncolumn of itsindex.csv(age_restricted,members_only,private,not_startedand others). The batch API reports an error code per task, and the script copies it intoerror_code, but I did not test those cases. - A channel export in the dashboard and in the Chrome extension is capped at 25 videos until you buy credits. The API has no such cap, only credits and rate limits. A free account is limited to 1 request per second and 100 requests per day, though, and this run makes about 70 to 80 requests, counting batch status polls, so check that limit before pointing the script at bigger channels.
Auto-generated captions also have their own gaps. The text contains sound tags such as [Music] (253 of them in this dataset), and spoken names get misspelled. Sourdough Sidekick's transcripts contain "croc" 42 times, a word I did not look into, and it could be a mis-heard term. The dataset is only as clean as YouTube's captions.
A first analysis
Save this as analyze.py. It uses only the standard library. It strips sound tags and common words, then prints per-channel totals, the most common terms, and terms a channel uses much more than the other two.
"""Word counts and most distinctive terms per channel, from dataset.csv."""
import csv
import math
import re
import sys
from collections import Counter, defaultdict
STOP = set("""a about above after again all also am an and any are as at be because been before being but by can
could did do does doing don down for from get got had has have having he her here him his how i if in into is it its
just like me more most my no not now of off on once one only or other our out over really she so some such than that
the their them then there these they this those through to too up us very was we were what when where which while who
will with would you your yeah okay oh um uh gonna want going know right think see let well kind sort bit lot thing
things way make little go back put take say much even still use good need actually pretty look something then's
that's it's i'm you're we're don't can't i'll i've let's there's""".split())
def tokens(text):
text = re.sub(r"\[[^\]]*\]", " ", text) # drop sound tags such as [Music]
return [w for w in re.findall(r"[a-z][a-z']+", text.lower()) if w not in STOP and len(w) > 2]
rows = [r for r in csv.DictReader(open(sys.argv[1], encoding="utf-8")) if r["status"] == "ok"]
by_channel = defaultdict(list)
for r in rows:
by_channel[r["channel_title"]].append(r)
counts = {c: Counter(w for r in rs for w in tokens(r["transcript"])) for c, rs in by_channel.items()}
doc_freq = Counter(w for c in counts for w in counts[c]) # in how many channels a term appears
total = {c: sum(n.values()) for c, n in counts.items()}
print(f"{'channel':28} {'videos':>6} {'words':>8} {'avg/video':>9} {'median s':>8} {'views/video':>11}")
for c, rs in by_channel.items():
words = sum(int(r["word_count"]) for r in rs)
lengths = sorted(int(r["length_seconds"]) for r in rs)
views = sum(int(r["view_count"]) for r in rs) / len(rs)
print(f"{c:28} {len(rs):6} {words:8} {words // len(rs):9} {lengths[len(lengths) // 2]:8} {views:11.0f}")
for c, n in counts.items():
print(f"\n{c}: most common terms")
print(", ".join(f"{w} ({k})" for w, k in n.most_common(12)))
# terms this channel uses far more than the others (smoothed log-ratio)
other = Counter()
for o, on in counts.items():
if o != c:
other.update(on)
other_total = sum(other.values())
score = {w: math.log(((k + 1) / (total[c] + 1)) / ((other[w] + 1) / (other_total + 1)))
for w, k in n.items() if k >= 8}
print("distinctive:", ", ".join(w for w, _ in sorted(score.items(), key=lambda x: -x[1])[:10]))Run python analyze.py dataset.csv. The most common terms, with counts, from my run:
| Channel | Most common terms |
|---|---|
| Sourdough Geeks | dough (82), bread (61), flour (50), loaf (33), fermentation (19) |
| Sourdough Sidekick | starter (108), flour (84), sidekick (81), water (81), sourdough (72) |
| Josh's Easy Sourdough | bread (143), dough (125), flour (115), starter (111), organic (95) |
The "distinctive" line compares each channel with the other two by the ratio of how often a word appears (with smoothing, only words used at least 8 times). It separates the channels better than raw counts:
- Sourdough Geeks: grayson, james, orleans, strength, bench, milling, bakery, mill. Titles show a "BREAD TALK" interview series with guest bakers, plus recipes.
- Sourdough Sidekick: sidekick, mode, calibration, press, cycle, menu, select, hopper. Tutorials for the Sourdough Sidekick, a sourdough starter appliance.
- Josh's Easy Sourdough: dad, organic, coconut, chicken, bones, protein. Family and grocery videos next to the recipes (one is titled "The Dad Days").
Those labels are my reading of the word lists plus the video titles, not something the script derives. With 62 videos from three channels, this shows the method works, not that these patterns would hold across the whole of YouTube's sourdough content. A real study needs more channels and a deliberate sampling rule. "Newest 40" is a choice that biases the sample toward recent uploads.
Notes for a larger run
- Cost scales at about 2 credits per video (stats plus transcript) plus 1 per 30 listed. A 5,000-video dataset is about 10,200 credits. If you only need transcripts, drop the video-info calls and it is about 1 per video.
- The batch API allows one running job and three queued per account, 100 tasks each. The script submits them one after another, so it stays inside that.
- Batch results are kept for 7 days, so write the CSV right away, as the script does.
- If you need a different caption language, add
languagesto each batch task as described in the transcript docs. This run left the default, which took each video's own language; all 60 were English auto-captions. - Videos without any caption track cannot be turned into text by any caption API. Speech-to-text on the audio is a separate step this script does not do. See what to do when a video has no captions.
- Check YouTube's terms and the creators' rights before publishing a dataset or training on it. Using transcripts for private analysis is a different thing from redistributing them.
Limits of this approach
- Credits cost money after the free 200. At the $9 pack (2,000 credits), the 126-credit run above is about 57 cents.
- View and like counts are a snapshot from the day you run it.
- Channel listing returns what YouTube shows on the channel's Videos tab. Shorts are a separate tab (
tab=shorts) that this script does not request. - If a channel has no captions on most videos, its row count will look healthy while its text is mostly empty. Always count
status = okper channel before comparing.