TikTokHow-to

How to scrape TikTok with Python: profiles, videos, comments

A free 297-line Python script scrapes public TikTok profiles, videos, comments and hashtags. It read 30 profiles in 14.5 seconds.

9 min read

Short answer

  • One Python file with curl_cffi reads public TikTok profiles, single videos, a creator's latest videos, a video's comments and hashtag totals, with no login or API key.
  • The script returns 11 videos per creator, top-level comments only (1,593 on a video showing 3,068) and at most 10 top videos per hashtag.
  • ToolzerHub's TikTok API pages a hashtag's videos, 109 to 174 unique videos in 4 to 7 pages on the tags we tried, at 1 credit a call.
On this page

You can scrape public TikTok profiles, videos, comments and hashtags with one Python file and no login: our free script toolzerhub/tiktok-scraper on GitHub. It is 297 lines and depends on one package, curl_cffi. It read 30 profiles in 14.5 seconds. It stops at 11 videos per creator and 10 top videos per hashtag.

Set up the TikTok scraper

Clone the repo, install curl_cffi and run profile on any public username. A profile page carries its data as JSON in one <script> tag, and a regular expression pulls it out, so no browser runs. Every command takes -o file.json to save the result.

bash
git clone https://github.com/toolzerhub/tiktok-scraper.git
cd tiktok-scraper
pip install -r requirements.txt
python tiktok_scraper.py profile nasa

Scrape a TikTok profile

Run profile with one or more usernames. It returns the bio, link in bio, verified and private flags, join date and exact follower, following, like and video counts. profile loads tiktok.com/@username and reads the webapp.user-detail scope. It prefers statsV2, which holds exact counts, over the older stats block that rounds big numbers.

python
    def profile(self, username):
        detail = self._page_scope(f"{BASE}/@{quote(username)}", "webapp.user-detail", f"profile {username}")
        info = (detail or {}).get("userInfo")
        if not info:
            raise ScrapeError(f"Profile not found: {username}")
        user = info["user"]
        # statsV2 has exact counts; the older "stats" block rounds big numbers.
        stats = info.get("statsV2") or info.get("stats") or {}

profile nasa took 0.8 seconds. Trimmed output:

json
{
  "id": "7664638705177150477",
  "username": "nasa",
  "url": "https://www.tiktok.com/@nasa",
  "nickname": "NASA",
  "bio": "Making the seemingly impossible, possible.✨",
  "bio_link": "science.nasa.gov/feature/artemis-ii-preliminary-lunar-science-report",
  "is_verified": true,
  "is_private": false,
  "created_at": "2026-07-20T15:55:49+00:00",
  "followers_count": 2097088,
  "following_count": 23,
  "likes_count": 11135867,
  "videos_count": 57,
  "avatar_url": "https://p16-common-sign.tiktokcdn-us.com/tos-useast5-avt-0068-tx/..."
}

Thirty accounts in one command, from nasa to tomholland, returned 30 of 30 in 14.5 seconds. The avatar link is signed and expires.

Get one video's stats

Run video with a video URL or just its numeric id. It returns the caption, hashtags, play, like, comment, share and save counts, the author and the sound. The id alone works because TikTok's page redirects any name to the real author, and the script sends _ as the name.

video 7665075736742530317 took 1.1 seconds and the full URL took 1.0. Trimmed output:

json
{
  "id": "7665075736742530317",
  "description": "Something big just landed on TikTok.",
  "created_at": "2026-07-21T20:09:02+00:00",
  "duration_seconds": 25,
  "hashtags": [],
  "play_count": 1600000,
  "like_count": 105100,
  "comment_count": 3068,
  "share_count": 3275,
  "save_count": 7630,
  "username": "nasa",
  "music_title": "original sound"
}

List a creator's videos

Run videos <username>. It returns about 11 of the creator's latest public videos, with no next page. The script reads TikTok's embed page for the creator, tiktok.com/embed/@nasa, the page other sites use for widgets. It holds a short video list as JSON.

python
    def _embed(self, path, what, missing="Not found or not public"):
        """Load a TikTok embed page and return its data block. HTTP 400 means no such item."""
        resp = self._get(f"{BASE}/embed/{path}", what, ok_statuses=(200, 400, 404))
        match = EMBED_DATA.search(resp.text)
        # ...
        # ...

videos nasa returned 11 videos in 1.0 second, and --limit 100 returned the same 11, while NASA's profile says 57. Each item has the caption, play count and links. --details opens each video page too, for exact likes, comments, shares and saves: 11 videos took 6.6 seconds.

TikTok is a class you can import, so several creators become one CSV. This script reuses one session and waits 2 seconds between creators. Save it next to the script.

python
import argparse
import csv
import os
import sys
import time

from tiktok_scraper import ScrapeError, TikTok

FIELDS = ["username", "id", "created_at", "play_count", "like_count", "comment_count",
          "share_count", "save_count", "duration_seconds", "hashtags", "description", "url"]


def main():
    parser = argparse.ArgumentParser(description="Latest videos of several creators, with exact counts, to one CSV.")
    parser.add_argument("output")
    parser.add_argument("usernames", nargs="+")
    parser.add_argument("--proxy", default=os.environ.get("HTTPS_PROXY"))
    args = parser.parse_args()

    tiktok = TikTok(args.proxy)  # one session for the whole list
    rows = 0
    with open(args.output, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS, extrasaction="ignore")
        writer.writeheader()
        for name in args.usernames:
            try:
                for video in tiktok.videos(name, details=True):
                    video["hashtags"] = " ".join(video["hashtags"])
                    writer.writerow(video)
                    rows += 1
            except ScrapeError as exc:
                print(f"{name}: {exc}", file=sys.stderr)
            time.sleep(2)  # pause between creators
    print(f"wrote {rows} videos to {args.output}")
    if rows == 0:
        sys.exit(1)


if __name__ == "__main__":
    main()

Run it as python videos_to_csv.py videos.csv nasa natgeo duolingo. The file has 33 rows, 11 per creator; two of them, with the second caption cut short:

csv
username,id,created_at,play_count,like_count,comment_count,share_count,save_count,duration_seconds,hashtags,description,url
nasa,7665075736742530317,2026-07-21T20:09:02+00:00,1600000,105100,3068,3275,7630,25,,Something big just landed on TikTok.,https://www.tiktok.com/@nasa/video/7665075736742530317
nasa,7697300954667994381,2026-10-16T16:19:26+00:00,101600,9862,253,293,777,121,,There was plenty to see across NASA this week 🚀 ...

Scrape a video's comments

Run comments <url> --limit N. It returns top-level comments with text, time, likes, reply count and author, from the JSON endpoint the TikTok web page uses, 50 a page. On long threads a page can come back empty mid-list, so the loop steps the cursor by 50 until three pages in a row add nothing, and skips repeats:

python
            new = 0
            for c in data.get("comments") or []:
                if c.get("cid") in seen:
                    continue
                seen.add(c.get("cid"))
                new += 1
                # ...
            # On long threads has_more turns false early and a page can come back
            # empty mid-list, so keep stepping until three pages in a row add nothing.
            empty = 0 if new else empty + 1
            cursor += 50

On the NASA video above, --limit 100 returned 100 comments in 1.1 seconds, and --limit 5000 returned 1,593 comments in 13.9 seconds. The 3,068 the video shows counts replies too, and the script returns a reply count, not the replies. How to get TikTok video comments compares the other ways to get them.

Scrape a TikTok hashtag

Run hashtag <name>. It returns the tag's id, total views and video count, and a short list of its top videos from the embed page tiktok.com/embed/tag/cooking. For #cooking it returned 556,307,836,550 views and 19,362,985 videos in 1.2 seconds, and --limit 5 gave 5 top videos. The embed page caps the list: #fyp returned 10 videos and #gardening 9 with --limit 50.

Some big tags, such as travel, don't come back from the embed page. TikTok counts 94,893,419 videos for it, and our API read it; the TikTok hashtag API guide shows that two-call flow and how deep a listing goes.

TikTok hashtags with ToolzerHub

We make ToolzerHub, and its TikTok API pages a hashtag's videos past the top 10 with one API key. Send hashtag=gardening to get TikTok's id for the tag, then that id as challenge_id:

bash
curl -H "x-api-key: $TOOLZERHUB_API_KEY" \
  "https://api.toolzerhub.com/v1/tiktok/hashtag?hashtag=gardening"

curl -H "x-api-key: $TOOLZERHUB_API_KEY" \
  "https://api.toolzerhub.com/v1/tiktok/hashtag_videos?challenge_id=186563&count=30"

The first call returned the tag's id, 186563. The second took 2.9 seconds and returned 30 videos with has_more true. Trimmed to one video:

json
{
  "data": {
    "entries": [
      {
        "id": "7691252206019923213",
        "desc": "4 easy diy garden hacks #garden #plant #gardening101 #veggies #harvest ",
        "create_time": 1790759220,
        "author": { "unique_id": "planthack3", "nickname": "PlantHack", "verified": false },
        "stats": { "play_count": 220400, "digg_count": 11800, "comment_count": 108, "share_count": 7414 },
        "hashtags": ["garden", "plant", "gardening101", "veggies", "harvest"]
      }
    ],
    "count": 30,
    "next_cursor": "30",
    "has_more": true
  }
}

Send each next_cursor back as cursor until has_more is false. This script does that, drops repeated videos and writes a CSV.

python
import csv
import os
import sys
from datetime import datetime, timezone

import requests

BASE = "https://api.toolzerhub.com/v1/tiktok"
HEADERS = {"x-api-key": os.environ.get("TOOLZERHUB_API_KEY", "")}


def get(path, **params):
    resp = requests.get(f"{BASE}/{path}", params=params, headers=HEADERS, timeout=60)
    resp.raise_for_status()
    return resp.json()["data"]


def list_page(**params):
    """One page of a hashtag's videos. Tries twice; None means the page kept failing."""
    for attempt in range(2):
        try:
            return get("hashtag_videos", **params)
        except requests.HTTPError:
            if attempt:
                return None


def main(tag, path):
    info = get("hashtag", hashtag=tag)  # 1 credit: TikTok's numeric id for the tag
    if not info:
        sys.exit(f"No such hashtag: {tag}")
    videos, rows, cursor, calls = {}, 0, 0, 1
    while True:
        page = list_page(challenge_id=info["id"], count=30, cursor=cursor)  # 1 credit a page
        if page is None:
            print("A page kept failing; saving what we have.")
            break
        calls += 1
        for v in page["entries"]:
            rows += 1
            videos.setdefault(v["id"], v)  # pages can repeat a video
        if not page["has_more"]:
            break
        cursor = page["next_cursor"]
    with open(path, "w", newline="", encoding="utf-8") as f:
        out = csv.writer(f)
        out.writerow(["id", "username", "created_at", "plays", "likes", "comments", "shares", "caption"])
        for v in videos.values():
            s = v["stats"]
            created = datetime.fromtimestamp(v["create_time"], timezone.utc).date().isoformat()
            out.writerow([v["id"], v["author"]["unique_id"], created, s["play_count"], s["digg_count"],
                          s["comment_count"], s["share_count"], v["desc"]])
    print(f"#{tag}: {len(videos)} videos ({rows - len(videos)} repeats dropped) in {calls} calls -> {path}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
bash
export TOOLZERHUB_API_KEY=your_key
python hashtag_videos.py cooking cooking.csv

It took 16.6 seconds, and its "calls" count is the tag lookup plus 5 pages:

text
#cooking: 141 videos (7 repeats dropped) in 6 calls -> cooking.csv

We walked 8 tags 12 times. Nine walks ended with has_more false after 118 to 188 entries (109 to 174 unique), in 4 to 7 pages. #cooking alone gave 118 to 145 entries across runs, so expect a different count each time. That is far past the script's 10, but not the whole tag: #gardening holds 4,370,345 videos by TikTok's count and its list stopped near 115. Pages repeat some videos, 103 of 1,310 entries, so deduplicate.

The tag travel returned 188 entries (174 unique) in 7 pages. music_videos takes the music_id that the script's video prints and lists videos that use that sound; the three sounds we paged returned 6, 7 and 13 videos. The script is the better pick for single records: our profile route returned NASA's followers as 2,100,000 where the script read about 2,097,000, and our video route has no save count, hashtags or upload time.

What it costs

Every TikTok call above costs 1 credit, so the #cooking run took 6 credits for 141 videos. You get 100 free credits a month; $19 buys 10,000 credits that never expire, and plans for higher volume cover more hashtags. Get a free API key and run the script on your first tag.

TikTok's own APIs are covered in what TikTok's official API allows. The same approach for Threads is in scraping Threads with Python.

We are not affiliated with TikTok Ltd. or ByteDance Ltd.

Get this data from your own code

The TikTok API returns it as JSON with one x-api-key header. 100 free credits monthly.