# YouTube comment scraper: comments and replies to CSV

This Python script saves a YouTube video's comments and replies to a CSV file. You get up to 20 comments a call at $0.0020. With full pages, 1,000 comments cost $0.10; replies are extra. A failed call is not charged.

Updated 2026-11-29

The [endpoint's page](https://dataxapi.com/apis/youtube/videos/comments/list/) covers a single request. Here you get page after page of comments and their replies in one file, up to a limit you set, without paying for the same replies twice.

## What one real run got

Run on 2026-11-29, exactly as printed below. “Me at the zoo” (`jNQXAC9IVRw`), the first video on YouTube: five pages of top comments, then one page of replies for each comment that had any, until it reached 20 calls. It made 20 calls, wrote 236 rows and cost $0.0400. There was more to get when it stopped.

Rows from the file it wrote. Comment text and IDs are left out here; the file has them.

```csv
id,parent_id,text,likes,replies
[ID],,[comment text],4800000,985
[ID],[comment ID],[comment text],58000,
[ID],[comment ID],[comment text],13000,
```

## The whole script

Save this as `export.py` and change the settings at the top. Install the SDK, set your key as the first two lines show, then run `python3 export.py`. You need Python 3.9 or later. The CSV file is saved in the folder you run it from. At the end, the script shows how many calls it made, how many rows it wrote and what was charged.

```python
# Python 3.9 or later. First: python3 -m pip install dataxapi
# and: export DATAXAPI_API_KEY=dx_...   (your key)
import csv
import sys
from decimal import Decimal
from dataxapi import APIConnectionError, DataXAPI, DataXAPIError

VIDEO = "jNQXAC9IVRw"   # the video's ID
COMMENT_PAGES = 5       # pages of top-level comments, 20 a page at most: 1 or more, or None for all there are
REPLY_PAGES = 1         # pages of replies under each comment: 0 for none, None for all there are
MAX_CALLS = 20          # the run stops here, whatever is left
OUT = "youtube_comments.csv"   # a new file: the run won't replace one
SHEET_SAFE = True       # puts ' before text a spreadsheet could run as a formula; False keeps it as it is

dx = DataXAPI()
calls, charged, seen, more, problem = 0, Decimal("0"), set(), False, None

class OutOfCalls(Exception):
    pass

def call(capability, params):
    """One call, never more than MAX_CALLS of them, failed ones included; adds up what they were charged."""
    global calls, charged
    if calls >= MAX_CALLS:
        raise OutOfCalls
    calls += 1
    result = dx.call(capability, params)
    charged += Decimal(str(result["meta"]["billing"]["amount"]))
    return result

def cell(value):
    """Text that begins as a formula does gets a ' before it, so a spreadsheet shows it and does not run it."""
    if SHEET_SAFE and isinstance(value, str) and value.lstrip(" ").startswith(("=", "+", "-", "@", "\t", "\r", "\n", "＝", "＋", "－", "＠")):
        return "'" + value
    return value

def pages(capability, params, most=None):
    """The items of each page, to the last one or to `most` pages; `more` turns true when some are left."""
    global more
    cursor, count = None, 0
    while True:
        result = call(capability, {**params, **({"cursor": cursor} if cursor else {})})
        yield result["data"]["items"]
        count += 1
        if not result["page"]["has_more"]:
            return
        if most is not None and count >= most:
            more = True
            return
        cursor = result["page"]["next_cursor"]

with open(OUT, "x", newline="", encoding="utf-8") as file:
    out = csv.writer(file)
    out.writerow(["id", "parent_id", "text", "likes", "replies"])

    def save(items, parent=""):
        """Writes the rows not written before, one at a time, and returns them."""
        new = []
        for item in items:
            if item["id"] in seen:
                continue
            metrics = item.get("metrics") or {}
            out.writerow([cell(item["id"]), cell(parent), cell(item["text"]), metrics.get("likes"), metrics.get("comments")])
            seen.add(item["id"])
            new.append(item)
        file.flush()
        return new

    threads = []
    try:
        # 1. The top-level comments. The full view has the token that gets a comment's replies.
        for items in pages("youtube.videos.comments.list", {"id": VIDEO, "sort": "popular", "view": "full"}, COMMENT_PAGES):
            for item in save(items):
                token = (item.get("ext") or {}).get("replies_token")
                replies = (item.get("metrics") or {}).get("comments")
                if REPLY_PAGES == 0 or replies == 0:
                    continue
                if token:
                    threads.append((item["id"], token))
                elif replies:
                    more = True   # it has replies, and nothing to get them with
        # 2. The replies under each comment that has any: at least one call a comment.
        for parent, token in threads:
            for items in pages("youtube.comments.replies.list", {"id": token}, REPLY_PAGES):
                save(items, parent)
    except OutOfCalls:
        more = True
    except (DataXAPIError, APIConnectionError) as error:
        problem = error

print(f"calls: {calls}, rows: {len(seen)}, charged: ${charged}" + (", and there is more to get" if more else ""))
if problem:
    print(f"Stopped by an error; the rows above are saved. {problem}")
    if problem.unsettled:
        print("The last call may have been charged. Check your call history before you run this again.")
    sys.exit(1)
```

### Open the file safely

Anyone can start a comment, caption or bio with `=`, `+`, `-` or `@`, and a spreadsheet may run it as a formula. `SHEET_SAFE` puts `'` before text like that. If you set it to `False`, don't open the file by double-clicking it. Some IDs are long numbers, which a spreadsheet may round. To keep them exact, use its CSV import and set the ID, handle and text columns to Text.

### If it stops early

`MAX_CALLS` counts every call, including failed ones. If the SDK tries a call again, it still counts as one. If a call fails, the script stops, keeps the rows it has and shows what it knows was charged. If the connection drops before an answer arrives, that call may still have been charged. The script tells you, so check your call history before you run it again. It never replaces a file: for another run, change `OUT` or move the old file.

## What it costs

| Job | Calls | Cost |
| --- | --- | --- |
| 1,000 comments, no replies | 50 | $0.10 |
| 1,000 comments, plus one page of replies for 300 of them | 350 | $0.70 |
| 10,000 comments, no replies | 500 | $1.00 |

These numbers assume 20 comments on every page. Replies usually cost more than comments because each comment that has replies needs at least one more call. A page usually has 10 replies. Prices are the ones in force when this page was built.

## What is in the file

| Column | What it is |
| --- | --- |
| `id` | The comment's or reply's ID |
| `parent_id` | For a reply, the ID of the comment it answers; empty for a comment |
| `text` | What it says |
| `likes` | Its likes. From 1,000 up, the number is rounded |
| `replies` | How many replies a comment has; empty for a reply |

## How it works

1. Put the video's ID in `VIDEO`: it is the part after `v=` in its link. `COMMENT_PAGES` is how many pages of comments to get. Top comments come first; change `popular` to `latest` for the newest first.
2. The script asks for the full view because it includes `ext.replies_token`, which gets a comment's replies. It stores one token for each comment that has replies. If a comment has replies but no token, the last line says there is more to get.
3. It then gets `REPLY_PAGES` pages of replies for each of those comments. With one page each, a busy comment can't use up all your calls. `0` skips replies. `None` gets every page, so the first busy comments may use all the calls you have left.
4. If a comment or reply appears twice, the script writes it once, and it gets the replies to each comment only once.

## What to know first

- This export has no dates. You can get the newest comments first, but you can't chart comments by day.
- You can get fewer comments than the count on the video. If comments are turned off, there are none to export.
- The file doesn't include names, but the words of a comment and its ID can still point to a person. Keep only what you need, and remove both before you share the file.
- A run starts from the first page. It can't pick up where an earlier run stopped, because the cursor for the next page works for an hour and isn't saved.

## Or ask your AI

With DataXAPI connected over MCP, say: Save the top 100 comments on https://www.youtube.com/watch?v=jNQXAC9IVRw and one page of replies to each to a CSV. Tell me the price first and stop at 20 calls.

## Endpoints used

- [YouTube video comments](https://dataxapi.com/apis/youtube/videos/comments/list/)
- [YouTube comment replies](https://dataxapi.com/apis/youtube/comments/replies/list/)

## More

- [YouTube API](https://dataxapi.com/apis/youtube/)
- [Facebook posts scraper: export a page's posts to CSV](https://dataxapi.com/exports/facebook-page-posts/)
- [Facebook comment scraper: recent posts to CSV](https://dataxapi.com/exports/facebook-post-comments/)
- [Instagram posts scraper: an account's posts to CSV](https://dataxapi.com/exports/instagram-posts/)
- [Instagram profile scraper: export from a list of handles](https://dataxapi.com/exports/instagram-profiles/)

---

Catalog revision ee799fed16791fcf. [HTML version](https://dataxapi.com/exports/youtube-comments/)
