Tutorial · TikTok · Python

Scrape TikTok comments to CSV with Python

To scrape TikTok comments with Python, page through /v1/tiktok/posts/{post}/comments with requests and keep a set of comment ids, because TikTok can repeat a few comments from one page on the next. The script below writes each comment once to a CSV and can fetch replies too.

Short answer. Run python tiktok_comments.py https://www.tiktok.com/@user/video/7300000000000000123 with HANDLEHAUL_API_KEY set. You get comments_7300000000000000123.csv: id, time, author, likes, reply count and text. About 20 comments per call: 1,000 comments take 50 calls, $0.070 to $0.040.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

What you need

  • An API key. Sign up and create one in the dashboard. A sandbox key (kd_test_) returns sample data for free, so you can run the script before you spend anything.
  • Python 3.9 or newer and the requests package (pip install requests). csv, os and the rest come with Python.
  • The key in HANDLEHAUL_API_KEY. The script reads it from the environment, so the key never sits in your code or your repository.
  • Public TikTok videos. The API returns public data only: no logins, no private accounts, no DMs.

The script

It calls GET /v1/tiktok/posts/{post}/comments and GET /v1/tiktok/comments/{comment}/replies (see the TikTok comments API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as tiktok_comments.py.

tiktok_comments.py
# Export every comment on a TikTok video to CSV, without duplicates.
# Usage: python tiktok_comments.py <video link or id> [max_pages]
# Needs Python 3.9+, the requests package and HANDLEHAUL_API_KEY in the environment.
import csv
import re
import os
import sys
import time
from urllib.parse import quote

import requests

API = "https://api.handlehaul.com"
KEY = os.environ.get("HANDLEHAUL_API_KEY")
if not KEY:
    sys.exit("Set HANDLEHAUL_API_KEY first, e.g. export HANDLEHAUL_API_KEY=kd_live_...")

session = requests.Session()
session.headers["X-Api-Key"] = KEY


class ApiError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"HTTP {status} {code}: {message}")
        self.status = status
        self.code = code


def get(path, params=None):
    # One API call. Waits and retries on 429 (honouring Retry-After) and on 502/503/504,
    # raises ApiError for any other error. Failed calls and 429 answers are not charged.
    for attempt in range(6):
        r = session.get(API + path, params=params, timeout=60)
        if r.status_code in (429, 502, 503, 504) and attempt < 5:
            try:
                wait = float(r.headers.get("Retry-After", ""))
            except ValueError:
                wait = 2 ** attempt
            print(f"  HTTP {r.status_code}, retrying in {wait:g}s", file=sys.stderr)
            time.sleep(wait)
            continue
        try:
            body = r.json()
        except ValueError:
            body = {}
        if r.ok:
            return body
        err = body.get("error") or {}
        raise ApiError(r.status_code, err.get("code", "unknown"), err.get("message", r.text[:200]))


FIELDS = ["id", "parent_id", "created_at", "handle", "nickname", "like_count", "reply_count", "text"]
INCLUDE_REPLIES = False  # True also fetches replies (about 3 per call) for comments that have them
MAX_REPLY_PAGES = 10     # per comment


def walk(path, params, max_pages):
    # Yields one page at a time, following pagination.next_cursor.
    params = dict(params)
    for _ in range(max_pages):
        body = get(path, params)
        yield body
        if not body["pagination"]["has_more"]:
            return
        params["cursor"] = body["pagination"]["next_cursor"]


def row(c):
    return {"id": c["id"], "parent_id": c.get("parent_id") or "", "created_at": c["created_at"],
            "handle": c["author"]["handle"], "nickname": c["author"]["nickname"],
            "like_count": c["like_count"], "reply_count": c.get("reply_count", 0), "text": c["text"]}


def main():
    if len(sys.argv) < 2:
        sys.exit("Usage: python tiktok_comments.py <video link or id> [max_pages]")
    post = sys.argv[1]
    max_pages = int(sys.argv[2]) if len(sys.argv) > 2 else 50  # about 20 comments a page
    m = re.search(r"/(?:video|photo)/(\d+)", post)
    out = f"comments_{m.group(1) if m else re.sub(r'[^0-9A-Za-z_-]', '_', post)[-40:]}.csv"
    path = f"/v1/tiktok/posts/{quote(post, safe='')}/comments"

    seen, calls, repeats, credits, error = set(), 0, 0, 0, None
    with open(out, "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        writer.writeheader()

        def save(comments):
            nonlocal repeats
            for c in comments:
                if c["id"] in seen:  # TikTok can repeat a few comments on the next page
                    repeats += 1
                    continue
                seen.add(c["id"])
                writer.writerow(row(c))

        try:
            for page in walk(path, {}, max_pages):
                calls += 1
                credits += page["meta"].get("credits_charged", 0)
                save(page["data"])
                if INCLUDE_REPLIES:
                    for c in page["data"]:
                        if c.get("reply_count", 0) > 0:
                            replies_path = f"/v1/tiktok/comments/{c['id']}/replies"
                            for rpage in walk(replies_path, {"post": post}, MAX_REPLY_PAGES):
                                calls += 1
                                credits += rpage["meta"].get("credits_charged", 0)
                                save(rpage["data"])
                print(f"{len(seen)} comments so far")
        except (ApiError, requests.RequestException) as e:
            error = e

    if error:
        sys.exit(f"Stopped: {error}\n{len(seen)} comments saved in {out}")
    print(f"Saved {len(seen)} comments to {out} ({repeats} repeats dropped, {calls} calls, {credits:g} credits)")


if __name__ == "__main__":
    main()
Tested 2026-12-02 against the documented API responses on Python 3.9.6. Run: python tiktok_comments.py https://www.tiktok.com/@river_wren29/video/7300000000000000123

Run it

  1. Get an API key. Sign up at api.handlehaul.com/signup and create a key. A sandbox key (kd_test_) returns sample data for free while you test.
  2. Set HANDLEHAUL_API_KEY. Export the key as the environment variable HANDLEHAUL_API_KEY so it never sits in the code.
  3. Install requests. Run pip install requests. Python 3.9 or newer is required; everything else is in the standard library.
  4. Save the script as tiktok_comments.py. Copy the script above into tiktok_comments.py.
  5. Run it. Run python tiktok_comments.py https://www.tiktok.com/@river_wren29/video/7300000000000000123. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
pip install requests
python tiktok_comments.py https://www.tiktok.com/@river_wren29/video/7300000000000000123
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

Paging. /v1/tiktok/posts/{post}/comments returns about 20 top-level comments a page, in TikTok’s order. The script follows pagination.next_cursor until has_more is false or max_pages is reached (50 by default, so about 1,000 comments).

Duplicates. TikTok can repeat a few comments from one page on the next. The script keeps a set of comment ids, writes each id once and reports how many repeats it dropped.

Replies. Set INCLUDE_REPLIES to true and, for each comment with reply_count above zero, the script calls /v1/tiktok/comments/{comment}/replies with ?post=. Replies come about 3 a page, so they cost more per row; on a reply, parent_id is the comment it answers.

Comments turned off. A video with comments off answers an empty page, so the file has only its header row.

Link or id. Paste the video link or the bare id. The output file is named after the video id.

What it costs

Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per page of about 20 comments; replies are one call per page of about 3. Failed calls and pages from the cache are free.

Calls and cost for export tiktok comments to csv
JobCallsCost
100 comments5$0.0070 to $0.0040
1,000 comments50$0.070 to $0.040
1,000 replies (about 3 a page)334$0.47 to $0.27

The script makes one call at a time, well under the account limit of 10 to 30 requests per second. Each response says what it cost in meta.credits_charged, and the script adds those up in its last line.

Sample output

An example run with example values, not a real export. Field names and shapes are the ones in the API docs.

Terminal
20 comments so far
39 comments so far
58 comments so far
Saved 58 comments to comments_7300000000000000123.csv (2 repeats dropped, 3 calls, 3 credits)
comments_7300000000000000123.csv
id,parent_id,created_at,handle,nickname,like_count,reply_count,text
7300000000000010123,,2026-11-30T00:53:20.000Z,aurora_cedar12,Aurora Cedar,50,0,Sample comment 1

Common errors

Errors come back as { "error": { "code", "message", "request_id" } } with an HTTP status. Failed calls are never charged. Full list: error codes.

Errors this script can meet and what it does
Status and codeWhenWhat the script does
404The video does not exist or was deletedStops. Free.
403 private_accountThe video belongs to a private accountStops. Free.
400 invalid_cursorA cursor from another videoStops. Start again without a cursor.
401 invalid_api_keyThe key is missing, wrong or revokedStops with the message. Check the variable with echo $HANDLEHAUL_API_KEY.
402 insufficient_creditsThe account is out of creditsStops. Rows already fetched stay in the file.
429 rate_limitedToo many requests per secondWaits for Retry-After and retries, up to 5 times. Not charged.
502 / 503 / 504Data temporarily unavailable or slowRetries with a growing wait (1, 2, 4, 8, 16 s). Failed calls are free.

The same job with the SDK

If you would rather not maintain the HTTP code, the official Python SDK (pip install handlehaul) does the paging, retries 429 for you and raises typed errors. The script above is the same job with every request visible.

Python SDK
# pip install handlehaul
from handlehaul import HandleHaul

hh = HandleHaul()  # reads HANDLEHAUL_API_KEY
seen = set()
for c in hh.tiktok.post_comments.iterate("7300000000000000123", max_pages=50):
    if c["id"] not in seen:
        seen.add(c["id"])
        print(c["author"]["handle"], c["text"])
Source and reference: handlehaul-python on GitHub.

Next steps

Export TikTok comments to CSV with Python: questions

Why are some comments repeated across pages?
TikTok sometimes repeats a few comments from one page at the top of the next. The API passes pages through as TikTok serves them, so the script keeps a set of ids and drops repeats.
How do I include replies?
Set INCLUDE_REPLIES = True. Replies come about 3 a page, so a video with many replies costs noticeably more; MAX_REPLY_PAGES caps it per comment.
Can I get comments from many videos at once?
Call main() in a loop, or wrap the body in a function that takes the link and returns the rows. Collect the video links first with /v1/tiktok/users/{user}/posts for an account.
What if comments are turned off?
The API answers an empty page, so the CSV has only the header row, and the call costs 1 credit like any successful page.

Run it on your own list

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.