TikTok scraper in Python: video views and likes to CSV
To scrape TikTok video stats with Python, send each video link to /v1/tiktok/posts/{post} with requests and write data.counts to a CSV. The script below reads a list of links and saves views, likes, comments, shares, saves, duration, caption and author for each, with the time it checked.
Short answer. Put one TikTok link or id per line in links.txt, set HANDLEHAUL_API_KEY and run python tiktok_video_stats.py links.txt. video_stats.csv gets one row per video. One call per video: 1,000 videos cost $1.40 to $0.80; links that no longer exist are free.
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} (see the TikTok post API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as tiktok_video_stats.py.
# Save views, likes, comments, shares and saves for a list of TikTok videos to CSV.
# Usage: python tiktok_video_stats.py links.txt (one video link or id per line)
# Needs Python 3.9+, the requests package and HANDLEHAUL_API_KEY in the environment.
import csv
from datetime import datetime, timezone
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 = ["input", "id", "url", "created_at", "views", "likes", "comments", "shares", "saves",
"duration_seconds", "author", "author_followers", "caption", "checked_at", "error"]
SKIP = {"user_not_found", "private_account"} # note these and go on (failed calls are free)
def main():
if len(sys.argv) < 2:
sys.exit("Usage: python tiktok_video_stats.py links.txt")
with open(sys.argv[1], encoding="utf-8") as f:
links = list(dict.fromkeys(line.strip() for line in f if line.strip() and not line.startswith("#")))
out = "video_stats.csv"
done, credits, error = 0, 0, None
with open(out, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=FIELDS)
writer.writeheader()
for link in links:
checked_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
try:
body = get(f"/v1/tiktok/posts/{quote(link, safe='')}")
except ApiError as e:
if e.code not in SKIP:
error = e
break
writer.writerow({"input": link, "checked_at": checked_at, "error": e.code})
print(f"{link}: {e.code}")
continue
except requests.RequestException as e:
error = e
break
p, c = body["data"], body["data"]["counts"]
credits += body["meta"].get("credits_charged", 0)
writer.writerow({
"input": link, "id": p["id"], "url": p["url"], "created_at": p["created_at"],
"views": c["views"], "likes": c["likes"], "comments": c["comments"], "shares": c["shares"],
"saves": c["saves"], "duration_seconds": p["duration_seconds"], "author": p["author"]["handle"],
"author_followers": (p["author"].get("counts") or {}).get("followers"),
"caption": p["caption"], "checked_at": checked_at, "error": "",
})
done += 1
print(f"{p['id']}: {c['views']} views, {c['likes']} likes")
if error:
sys.exit(f"Stopped: {error}\n{done} videos saved in {out}")
print(f"Saved {done} of {len(links)} videos to {out} ({credits:g} credits)")
if __name__ == "__main__":
main()
python tiktok_video_stats.py links.txtRun 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_video_stats.py. Copy the script above into
tiktok_video_stats.py, and put your input inlinks.txt, one item per line. - Run it. Run
python tiktok_video_stats.py links.txt. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
Example links.txt:
https://www.tiktok.com/@river_wren29/video/7300000000000000123
7300000000000000456
export HANDLEHAUL_API_KEY=kd_live_... # your key from the dashboard
pip install requests
python tiktok_video_stats.py links.txt
$env:HANDLEHAUL_API_KEY="kd_live_...".How it works
One call per video. The script calls /v1/tiktok/posts/{post} with the video id, or the full link URL-encoded into the path (https%3A%2F%2Fwww.tiktok.com%2F…). Both work; the script encodes whatever is on the line.
The counts. data.counts holds views, likes, comments, shares and saves. The script also keeps duration_seconds, the caption, the author’s handle and follower count (data.author.counts.followers).
Snapshots. Every row gets a checked_at time in UTC. Run the script on a schedule and keep each day’s file to see how a video’s numbers grow.
Missing videos. A video that does not exist answers 404 with the code user_not_found (that is the code the API uses for posts too). The script writes it in the error column and goes on, and the call is free.
Many videos from one account? /v1/tiktok/users/{user}/posts returns a page of an account’s videos with the same counts in one call, which costs far less than one call per video.
What it costs
Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per video that exists. Videos that do not exist and answers from the cache are free.
| Job | Calls | Cost |
|---|---|---|
| 100 videos | 100 | $0.14 to $0.080 |
| 1,000 videos | 1,000 | $1.40 to $0.80 |
| 100 videos, daily for 30 days | 3,000 | $4.20 to $2.40 |
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.
7300000000000000123: 538234 views, 32294 likes
7300000000000000456: user_not_found
Saved 1 of 2 videos to video_stats.csv (1 credits)
input,id,url,created_at,views,likes,comments,shares,saves,duration_seconds,author,author_followers,caption,checked_at,error
https://www.tiktok.com/@river_wren29/video/7300000000000000123,7300000000000000123,https://www.tiktok.com/@river_wren29/video/7300000000000000123,2026-07-30T00:53:20.000Z,538234,32294,1076,538,1615,18,river_wren29,579298,Sample post 124 by @river_wren29 #pixel #fyp,2026-12-02T09:00:00Z,
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 user_not_found | The video does not exist or was deleted | The script writes a row with the error code and goes on (failed calls are free). |
403 private_account | The video belongs to a private account | The script writes a row with the error code and goes on (failed calls are free). |
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
p = hh.tiktok.post("7300000000000000123").data
print(p["counts"]["views"], p["counts"]["likes"], p["counts"]["shares"])
Next steps
- TikTok video views and likes to CSV with Node.js: the same script in Node.js.
- TikTok video API: what the endpoint returns and how it compares.
- TikTok post API docs: every parameter, field and error.
- All tutorials: other jobs on Instagram and TikTok, in Python and Node.js.
TikTok video views and likes to CSV with Python: questions
Can I scrape TikTok with Python without Selenium or a browser?
How do I track a video’s views every day?
out to f"video_stats_{date.today()}.csv". The checked_at column tells the runs apart.Can I calculate an engagement rate from this?
Does it work for photo posts?
media_type is “photo” and images lists the pictures. Add those fields to FIELDS if you need them.Related
TikTok video API
One video or a whole profile’s videos, with every count.
Read more →The same in Node.js
TikTok video views and likes to CSV with Node.js: same output, built-in fetch, no packages.
Read more →Free TikTok view counter
Check views, likes and shares for up to 10 links in the browser, no key.
Read more →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.