YouTube

How to Scrape YouTube Comments (Python and JavaScript)

Export the comments of a YouTube video to JSON or CSV with authors, likes, dates and replies, without a browser or quota. Code in curl, Python and JavaScript.

By FetchTranscript teamPublished Updated 6 min read

To scrape YouTube comments, send the video ID to an endpoint that reads the comment threads for you and returns them as JSON: one HTTP request gives up to 500 top-level comments with author, likes, reply count, date and pinned flag. This guide shows how to do it with curl, Python and JavaScript, how to add replies, how to export to CSV, and what the free alternatives (the YouTube Data API, yt-dlp, a headless browser) cost you in time and quota.

Why scraping YouTube comments is harder than it looks

Comments are not in the HTML of a watch page. YouTube loads them lazily, a batch at a time, through internal requests that need a continuation token taken from the previous batch. Replies live behind another token per thread. A browser does all of this as you scroll; a script has to imitate it, and the format of those internal responses changes without notice.

On top of that, YouTube rate-limits and challenges traffic that looks automated, especially from cloud servers. A script that works on your laptop for ten videos often starts failing on a server at a few hundred. That is the part that eats engineering time: not parsing, but keeping the pipeline alive.

You have four realistic options:

OptionSetupLimitsGood for
YouTube Data API v3 (commentThreads.list)Google Cloud project, API key10,000 units per day by default, 1 unit per page of up to 100 threadsSmall volumes, official data
yt-dlp (--write-comments)Free, open sourceSlow, downloads one video at a time, blocked from many server IPsOne-off exports on your own machine
Headless browser (Playwright, Puppeteer)You write and maintain the scrollerHeavy, fragile, easy to detectAlmost never worth it for comments
A hosted comments APIAPI keyPay per comment volumePipelines, dashboards, research at scale

The official API is a fair choice if you only need a few thousand pages a day and can live with its quota. The rest of this guide uses the YouTube Comments API of FetchTranscript, which handles the continuation tokens, retries and proxies on its side.

Get the comments of a video with curl

You need an API key: create a free account and copy the key from the dashboard (it starts with yt_). Then:

Shell
curl -H "X-API-Key: yt_your_api_key" \
  "https://api.fetchtranscript.com/v1/videos/dQw4w9WgXcQ/comments?limit=100&sort=top"

The response looks like this:

JSON
{
  "video_id": "dQw4w9WgXcQ",
  "comments": [
    {
      "comment_id": "UgzX...",
      "text": "Still a masterpiece.",
      "author": "@someviewer",
      "author_id": "UC...",
      "like_count": 1520,
      "reply_count": 34,
      "published_at": "2025-06-14T00:00:00Z",
      "is_pinned": false
    }
  ],
  "total_count": 2400000,
  "has_more": true
}

The parameters are few:

  • limit: how many top-level comments to return, from 1 to 500 (default 100).
  • sort: top (YouTube's top comments, the default) or new (newest first).
  • include_replies and replies_per_comment: covered below.

A few fields deserve a word. total_count is the comment count YouTube shows under the video, and it includes replies, so it is usually larger than the number of top-level comments you can fetch. has_more is true when the page came back full and there are more comments. published_at is an ISO-8601 UTC estimate: YouTube only displays relative times such as "3 days ago" or "2 years ago", so the date is computed from that text. It is precise for recent comments and approximate (to the month or year) for old ones. Do not use it for anything that needs exact timestamps.

Scrape YouTube comments with Python

With requests, handling the errors you will actually meet:

Python
import requests

API_KEY = "yt_your_api_key"
BASE = "https://api.fetchtranscript.com/v1"

def get_comments(video_id, limit=500, sort="top"):
    response = requests.get(
        f"{BASE}/videos/{video_id}/comments",
        headers={"X-API-Key": API_KEY},
        params={"limit": limit, "sort": sort},
        timeout=60,
    )
    if response.status_code == 404:
        error = response.json()["detail"]["error"]
        if error == "comments_disabled":
            return []  # the owner turned comments off; the call costs nothing
        raise ValueError(f"{video_id}: {error}")
    response.raise_for_status()
    print("credits used:", response.headers.get("X-Credits-Used"))
    return response.json()["comments"]

comments = get_comments("dQw4w9WgXcQ")
for c in comments[:5]:
    print(c["like_count"], c["author"], c["text"][:80])

If you prefer the official SDK (pip install fetchtranscript), the same call is one line:

Python
from fetchtranscript import FetchTranscriptClient

client = FetchTranscriptClient(api_key="yt_your_api_key")
page = client.videos.get_comments("dQw4w9WgXcQ", limit=500, sort="new")
print(len(page["comments"]), "comments, has_more:", page["has_more"])

Scrape YouTube comments with JavaScript

Node 18 and later have fetch built in, so no dependency is needed:

JavaScript
// Node 18+ as an ES module (a .mjs file, or "type": "module"), for the top-level await
const API_KEY = 'yt_your_api_key';

async function getComments(videoId, { limit = 100, sort = 'top' } = {}) {
  const url = new URL(`https://api.fetchtranscript.com/v1/videos/${videoId}/comments`);
  url.searchParams.set('limit', String(limit));
  url.searchParams.set('sort', sort);
  const res = await fetch(url, { headers: { 'X-API-Key': API_KEY } });
  if (res.status === 429) {
    const wait = Number(res.headers.get('Retry-After') || 5);
    await new Promise((r) => setTimeout(r, wait * 1000));
    return getComments(videoId, { limit, sort });
  }
  const body = await res.json();
  if (!res.ok) throw new Error(`${body.detail.error}: ${body.detail.message}`);
  return body;
}

const { comments, total_count } = await getComments('dQw4w9WgXcQ', { limit: 200 });
console.log(`${comments.length} of about ${total_count} comments`);

Include the replies

By default you get top-level comments only, each with its reply_count. Add include_replies=true and every comment carries a replies list (empty when it has none), with up to replies_per_comment replies each (1 to 100, default 10), in YouTube's order:

Shell
curl -H "X-API-Key: yt_your_api_key" \
  "https://api.fetchtranscript.com/v1/videos/dQw4w9WgXcQ/comments?limit=50&include_replies=true&replies_per_comment=20"

Each reply has comment_id, parent_id (the comment it answers), text, author, author_id, like_count and published_at. limit still counts top-level comments only. These calls are slower, because each thread needs one more request to YouTube, so only ask for replies when you need the conversation, for example to study how a creator answers questions.

What it costs

Comments are billed by volume rather than per call: 1 credit per 100 items returned, rounded up, minimum 1. Items are comments plus replies. So:

  • 100 comments cost 1 credit, 101 to 200 cost 2, a full page of 500 costs 5.
  • 60 comments with 60 replies are 120 items, so 2 credits.
  • A video with comments turned off answers 404 comments_disabled and costs nothing. Every failed call is free.

The X-Credits-Used header tells you what each call cost and X-Credits-Remaining what is left. Every account gets 100 free credits a month, then it is $1 per 1,000 credits, so 100,000 comments cost about $1. If your balance can only pay for part of a request, you get as many comments as it covers and has_more is true. Details are on the pricing page.

Export YouTube comments to CSV

Most people want the comments in a spreadsheet. This script writes one row per comment and per reply, with the parent ID so you can rebuild the threads:

Python
import csv
import requests

API_KEY = "yt_your_api_key"

def export_comments(video_id, path):
    response = requests.get(
        f"https://api.fetchtranscript.com/v1/videos/{video_id}/comments",
        headers={"X-API-Key": API_KEY},
        params={"limit": 500, "include_replies": "true", "replies_per_comment": 10},
        timeout=120,
    )
    response.raise_for_status()
    with open(path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["comment_id", "parent_id", "author", "likes", "published_at", "text"])
        for c in response.json()["comments"]:
            writer.writerow([c["comment_id"], "", c["author"], c["like_count"], c["published_at"], c["text"]])
            for r in c.get("replies") or []:
                writer.writerow([r["comment_id"], r["parent_id"], r["author"], r["like_count"], r["published_at"], r["text"]])

export_comments("dQw4w9WgXcQ", "comments.csv")

If you only need the text for analysis, do not keep the authors at all: replace the c["author"] and r["author"] columns with a pseudonym such as hashlib.sha256((salt + (c["author_id"] or c["author"])).encode()).hexdigest()[:12] (with a secret salt of your own and import hashlib), or leave them out. You can still count how many distinct people commented without storing who they are.

Open the file with UTF-8 encoding: comments are full of emoji and non-Latin scripts, and spreadsheet apps that guess the encoding will garble them.

Scraping comments of many videos

For a channel or a list of videos, first collect the video IDs (see how to get all videos from a YouTube channel or the search guide), then loop. Keep these rules in mind:

  1. Stay under 500 requests per minute. A 429 rate_limit_exceeded comes with a Retry-After header: wait that many seconds and retry.
  2. Retry 503 service_unavailable with backoff; it is temporary.
  3. Treat 404 comments_disabled and video_not_found as final and move on.
  4. Store the comment_id: it is stable, so a second run can skip what you already have.

To track new comments over time, call with sort=new and stop reading once you meet a comment_id you already stored.

What people do with YouTube comments

Comments are one of the few places where an audience says what it thinks in its own words. Common uses:

  • Sentiment and topic analysis of a launch, a trailer or a competitor's videos.
  • Product feedback mining: feature requests and bug reports hidden in tutorial comments.
  • Content research: the questions viewers ask become your next video or article.
  • Moderation and spam studies, and academic research on online discourse.

Pair the comments with the video's metadata (views, likes, upload date) to normalise engagement across videos. If you work with personal data such as usernames, read our guide to the legal side of scraping YouTube first.

Frequently asked questions

Can I scrape YouTube comments without an API key?

With yt-dlp or a browser you can, on your own machine and at low volume. For anything regular or on a server you need either a Google API key with its daily quota or a hosted API key; you can try the comments endpoint free without an account.

How many comments can I get per video?

Up to 500 top-level comments per request, in top or newest order, each with up to 100 replies when you ask for them. total_count shows how many YouTube reports, replies included.

Why is published_at not exact?

YouTube only shows relative times such as "2 weeks ago", so the date is an estimate computed from that text. It is close for recent comments and approximate for old ones.

Do I pay for videos with comments disabled?

No. They answer 404 comments_disabled, and every failed call costs zero credits.

Is there a Python package?

Yes: pip install fetchtranscript, then client.videos.get_comments(video_id, limit=..., sort=...). See the SDK docs and the API reference.

Try it on your own videos

100 free calls every month, no credit card. Then $1 per 1,000 calls, only for the calls that succeed.

← All articles