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
requestspackage (pip install requests).csv,osand 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.
# 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()
python tiktok_comments.py https://www.tiktok.com/@river_wren29/video/7300000000000000123Run it
- 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. - Set HANDLEHAUL_API_KEY. Export the key as the environment variable
HANDLEHAUL_API_KEYso it never sits in the code. - Install requests. Run
pip install requests. Python 3.9 or newer is required; everything else is in the standard library. - Save the script as tiktok_comments.py. Copy the script above into
tiktok_comments.py. - 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.
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
$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.
| Job | Calls | Cost |
|---|---|---|
| 100 comments | 5 | $0.0070 to $0.0040 |
| 1,000 comments | 50 | $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.
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)
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.
| Status and code | When | What the script does |
|---|---|---|
404 | The video does not exist or was deleted | Stops. Free. |
403 private_account | The video belongs to a private account | Stops. Free. |
400 invalid_cursor | A cursor from another video | Stops. Start again without a cursor. |
401 invalid_api_key | The key is missing, wrong or revoked | Stops with the message. Check the variable with echo $HANDLEHAUL_API_KEY. |
402 insufficient_credits | The account is out of credits | Stops. Rows already fetched stay in the file. |
429 rate_limited | Too many requests per second | Waits for Retry-After and retries, up to 5 times. Not charged. |
502 / 503 / 504 | Data temporarily unavailable or slow | Retries 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.
# 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"])
Next steps
- Scrape TikTok comments to CSV with Node.js: the same script in Node.js.
- TikTok comments API: what the endpoint returns and how it compares.
- TikTok comments API docs: every parameter, field and error.
- All tutorials: other jobs on Instagram and TikTok, in Python and Node.js.
Export TikTok comments to CSV with Python: questions
Why are some comments repeated across pages?
How do I include replies?
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?
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?
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.