TikTok Scraper Python: How to Validate Product Demand Before You Source Inventory
You can test whether a product idea has real, current demand on TikTok before you buy stock — by collecting public video records for each candidate term and scoring six measurable signals: video volume, median views, median engagement, creator breadth, recency share, and commercial-intent share. This guide is for e-commerce operators, dropshippers, and product researchers who are tired of guessing from a handful of viral clips, and who want a repeatable shortlist instead of a gut feeling.
The workflow uses two repositories from the data-scrape account: a TikTok data scraper API with video, profile, comment, and hashtag endpoints for scheduled collection, and a TikTok video scraper for per-video metrics and trending discovery when you only need video records. The repositories handle collection. The scoring layer below is the part that decides whether you wire a supplier a deposit.
TL;DR
- Pick 4-10 candidate product terms. More than ten and you dilute attention; fewer than four and the relative scoring has nothing to compare.
- Collect public video records per term: views, likes, comments, shares, author, caption, timestamp.
- Score six signals, not one. A single viral video is not demand; a broad, recent, engaged creator base is.
- Gate every product behind a minimum sample size. Below that threshold, the correct verdict is "insufficient sample", not "promising".
- Save each run as a dated JSONL file, then compare scores week over week. Direction beats any single snapshot.
- Treat the output as a shortlist for further research, never as a sales forecast.
Why "it went viral" is the wrong signal
The default research method is scrolling TikTok, spotting three clips with big view counts, and concluding the product is hot. That method fails for four reasons that are easy to fix once you name them.
One clip is an anecdote. A single video with a million views tells you one creator's audience reacted, or that one account paid for distribution. It says nothing about whether thousands of ordinary buyers want the item.
Views are not intent. Entertainment formats earn enormous view counts with zero purchase intent. A product demo that earns 40,000 views from people commenting "where do I buy this" is worth more than a comedy clip with 2 million.
The trend may already be over. TikTok feeds surface evergreen and stale content side by side. If most of the videos you see were posted eight months ago, you are looking at a trend that already peaked — and your inventory would arrive after the wave.
Manual counting does not compound. Two weeks later you cannot answer "is this still growing?" because you have impressions, not a dataset. The fix is one normalized record set, collected the same way every time.
The six signals, and what each one catches
| Signal | Definition in this workflow | What it catches |
|---|---|---|
| Video volume | Distinct videos per term after de-duplication by video ID | Attention supply — how much content the term generates |
| Median views | Median of view counts across the sample | Typical reach, not outlier reach |
| Engagement rate | Median of (likes + comments + shares) / views per video | Whether viewers react or just scroll past |
| Creator breadth | Unique authors ÷ videos | Organic spread versus a handful of accounts pushing one item |
| Recency share | Share of videos created within the last 30 days | Whether interest is current or decaying |
| Commercial-intent share | Share of captions containing buy-intent phrases | How saturated the term already is with sellers and affiliates |
Two choices matter. Medians instead of averages, because one 10-million-view clip drags a mean into fantasy while the median stays honest. And creator breadth, because a term where 40 videos come from 3 accounts is a marketing push, not a market.
The combination is where the reading happens:
- High volume + high breadth + high recency = broad, current, organic interest.
- High views + low breadth = concentrated distribution. Verify before you trust it.
- High commercial share + low engagement = the term is already crowded with affiliate spam. Expect price competition and thin margin.
- High historical views + low recency = the wave has passed.
The repositories, and which one to use when
Both projects are Python, MIT-licensed, and installable from source. They overlap on purpose but serve different shapes of work.
The TikTok data scraper API repository is the service-oriented option. Its README documents a REST surface with endpoints for videos, profiles, comments, and hashtags, JSON responses with pagination, API-key authentication and rate limiting, Docker deployment, Swagger docs, and webhook support for async jobs. Use it when collection runs on a schedule and other systems consume the output.
The TikTok video scraper repository is the record-oriented option. Its README documents per-video extraction of views, likes, shares, and comments, captions and hashtags, sound information, creator profile data, and trending video discovery. Use it when your job is "give me the video records for these terms" and you do not need a running service.
A practical split: the API repo is your weekly cron job, the video scraper your ad-hoc exploration tool. Both expose a Scraper class with a scrape(query) method and a CLI accepting --query and --output, so switching is a one-line import change below.
Neither repository is an official TikTok product, and neither promises coverage, quota, or uptime. Confirm the current invocation, output format, and usage limits on the README before depending on them.
Setup
Python 3.8+ is enough. Install whichever client you plan to collect with:
pip install git+https://github.com/data-scrape/tiktok-data-scraper-api.git
# or, for the video-only client:
pip install git+https://github.com/data-scrape/tiktok-video-scraper.git
Configuration lives in environment variables, never in the file:
export PRODUCTS="portable blender,sunset lamp,pet hair remover,mini projector"
export COLLECT_LIVE="0" # "1" to collect through the repository client
export MIN_SAMPLE="20" # refuse to rank a term below this many videos
export RECENCY_DAYS="30"
# If your deployment requires API-key authentication, export it under the
# variable name documented in the repository README. Do not hardcode it.
export TIKTOK_API_KEY="set-me-from-your-secret-store"
With COLLECT_LIVE=0, the script runs entirely on the embedded example records — which means you can verify the scoring logic before you touch collection, and you get a deterministic output to test your downstream sheet against.
The scoring script
This is the whole pipeline: collect, normalize, score, rank, persist. It is runnable as-is and uses only the standard library.
"""Score public TikTok demand signals for candidate products."""
import json
import os
import re
import statistics
from datetime import datetime, timedelta, timezone
COLLECT_LIVE = os.environ.get("COLLECT_LIVE", "0") == "1"
MIN_SAMPLE = int(os.environ.get("MIN_SAMPLE", "20"))
RECENCY_DAYS = int(os.environ.get("RECENCY_DAYS", "30"))
RUN_DATE = datetime.now(timezone.utc)
PRODUCTS = [p.strip() for p in os.environ.get(
"PRODUCTS", "portable blender,sunset lamp,pet hair remover,mini projector"
).split(",") if p.strip()]
COMMERCIAL_TOKENS = ("link in bio", "shop now", "where to buy", "sold out",
"restock", "amazon finds", "tiktok shop")
# EXAMPLE records only. Replace with collected records; metrics below are not
# claims about real products or creators.
SAMPLE = {
"portable blender": [
{"id": "v101", "author": "u_a", "views": 482000, "likes": 51200, "comments": 913, "shares": 7400,
"caption": "smoothie in 20 seconds #portableblender link in bio", "created_at": "2026-11-18T10:12:00Z"},
{"id": "v102", "author": "u_b", "views": 96000, "likes": 8100, "comments": 214, "shares": 1100,
"caption": "portable blender test #gadgets", "created_at": "2026-11-20T08:40:00Z"},
{"id": "v103", "author": "u_c", "views": 1240000, "likes": 143000, "comments": 3200, "shares": 21000,
"caption": "this portable blender is everywhere #tiktokmademebuyit", "created_at": "2026-11-12T17:05:00Z"},
{"id": "v104", "author": "u_a", "views": 73000, "likes": 5400, "comments": 88, "shares": 410,
"caption": "portable blender restock alert", "created_at": "2026-11-22T12:00:00Z"},
{"id": "v105", "author": "u_d", "views": 228000, "likes": 19700, "comments": 640, "shares": 2600,
"caption": "portable blender vs bullet blender", "created_at": "2026-10-02T09:30:00Z"},
],
"sunset lamp": [
{"id": "v201", "author": "u_e", "views": 31000, "likes": 2100, "comments": 61, "shares": 180,
"caption": "sunset lamp room tour", "created_at": "2026-11-19T20:15:00Z"},
{"id": "v202", "author": "u_f", "views": 18000, "likes": 980, "comments": 24, "shares": 70,
"caption": "sunset lamp aesthetic #roomdecor", "created_at": "2026-11-21T19:40:00Z"},
{"id": "v203", "author": "u_g", "views": 52000, "likes": 3900, "comments": 130, "shares": 300,
"caption": "sunset lamp unboxing", "created_at": "2026-09-28T11:10:00Z"},
{"id": "v204", "author": "u_e", "views": 12000, "likes": 640, "comments": 12, "shares": 40,
"caption": "sunset lamp giveaway", "created_at": "2026-11-05T18:00:00Z"},
],
"pet hair remover": [
{"id": "v301", "author": "u_h", "views": 890000, "likes": 96000, "comments": 4100, "shares": 15000,
"caption": "pet hair remover on the couch #cleantok", "created_at": "2026-11-16T14:20:00Z"},
{"id": "v302", "author": "u_i", "views": 410000, "likes": 38000, "comments": 1200, "shares": 5200,
"caption": "pet hair remover before and after", "created_at": "2026-11-23T09:05:00Z"},
{"id": "v303", "author": "u_j", "views": 156000, "likes": 12800, "comments": 470, "shares": 1900,
"caption": "pet hair remover where to buy #amazonfinds", "created_at": "2026-11-24T16:45:00Z"},
{"id": "v304", "author": "u_k", "views": 62000, "likes": 5400, "comments": 190, "shares": 610,
"caption": "pet hair remover honest review", "created_at": "2026-11-11T07:50:00Z"},
{"id": "v305", "author": "u_l", "views": 240000, "likes": 47000, "comments": 2600, "shares": 8800,
"caption": "my cat destroys the couch, pet hair remover saves it", "created_at": "2026-11-02T13:30:00Z"},
],
"mini projector": [
{"id": "v401", "author": "u_m", "views": 15000, "likes": 700, "comments": 18, "shares": 45,
"caption": "mini projector movie night", "created_at": "2026-08-14T21:00:00Z"},
{"id": "v402", "author": "u_n", "views": 9000, "likes": 410, "comments": 9, "shares": 22,
"caption": "mini projector setup", "created_at": "2026-07-30T22:10:00Z"},
{"id": "v403", "author": "u_o", "views": 22000, "likes": 1300, "comments": 35, "shares": 90,
"caption": "mini projector comparison", "created_at": "2026-09-19T20:00:00Z"},
],
}
def collect(product):
"""Pull public video records for one query through the repository client."""
from tiktok_data_scraper_api import Scraper # pip install git+<repo-url>
return Scraper().scrape(product) or []
def to_int(value):
"""Accept 1240000 or '1.24M' / '96K' style counts."""
if isinstance(value, (int, float)):
return int(value)
text = str(value or "").strip().upper().replace(",", "")
match = re.match(r"^([\d.]+)\s*([KMB]?)$", text)
if not match:
return 0
number = float(match.group(1))
return int(number * {"": 1, "K": 1_000, "M": 1_000_000, "B": 1_000_000_000}[match.group(2)])
def parse_ts(value):
if not value:
return None
try:
return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
def normalize(records):
seen, out = set(), []
for row in records:
video_id = row.get("id") or row.get("video_id")
if video_id and video_id in seen:
continue
if video_id:
seen.add(video_id)
out.append({
"id": video_id,
"author": (row.get("author") or row.get("username") or "").lower(),
"views": to_int(row.get("views") or row.get("play_count")),
"likes": to_int(row.get("likes")),
"comments": to_int(row.get("comments")),
"shares": to_int(row.get("shares")),
"caption": (row.get("caption") or row.get("desc") or "").lower(),
"created_at": parse_ts(row.get("created_at")),
})
return out
def metrics_for(records):
if not records:
return None
views = [r["views"] for r in records]
engagements = [(r["likes"] + r["comments"] + r["shares"]) / r["views"]
for r in records if r["views"] > 0]
cutoff = RUN_DATE - timedelta(days=RECENCY_DAYS)
dated = [r for r in records if r["created_at"]]
recent = [r for r in dated if r["created_at"] >= cutoff]
commercial = [r for r in records if any(t in r["caption"] for t in COMMERCIAL_TOKENS)]
authors = {r["author"] for r in records if r["author"]}
return {
"videos": len(records),
"authors": len(authors),
"median_views": int(statistics.median(views)),
"engagement_rate": round(statistics.median(engagements), 4) if engagements else 0.0,
"creator_breadth": round(len(authors) / len(records), 2),
"recent_share": round(len(recent) / len(dated), 2) if dated else None,
"commercial_share": round(len(commercial) / len(records), 2),
}
def minmax(values):
low, high = min(values), max(values)
if high == low:
return [0.5 for _ in values]
return [(v - low) / (high - low) for v in values]
WEIGHTS = {"videos": 0.25, "median_views": 0.20, "engagement_rate": 0.20,
"creator_breadth": 0.15, "recent_share": 0.10, "commercial_share": 0.10}
def score(products):
rows = []
for name in products:
raw = collect(name) if COLLECT_LIVE else SAMPLE.get(name, [])
m = metrics_for(normalize(raw))
rows.append({"product": name, **m} if m else {"product": name, "videos": 0, "verdict": "no data"})
scored = [r for r in rows if r.get("videos")]
for key in ("videos", "median_views", "engagement_rate", "creator_breadth", "commercial_share"):
for row, value in zip(scored, minmax([r[key] for r in scored])):
row[f"_{key}"] = value
recency = [r["recent_share"] if r["recent_share"] is not None else 0.0 for r in scored]
for row, value in zip(scored, minmax(recency)):
row["_recent_share"] = value
for row in scored:
row["demand_score"] = round(100 * sum(WEIGHTS[k] * row[f"_{k}"] for k in WEIGHTS), 1)
if row["videos"] < MIN_SAMPLE:
row["verdict"] = "insufficient sample"
elif row["demand_score"] >= 70:
row["verdict"] = "strong candidate"
elif row["demand_score"] >= 45:
row["verdict"] = "promising"
else:
row["verdict"] = "weak"
for key in [k for k in row if k.startswith("_")]:
del row[key]
return sorted(rows, key=lambda r: r.get("demand_score", -1), reverse=True)
if __name__ == "__main__":
results = score(PRODUCTS)
stub = f"tiktok-demand-{RUN_DATE:%Y-%m-%d}.jsonl"
with open(stub, "w", encoding="utf-8") as fh:
for row in results:
print(json.dumps(row))
fh.write(json.dumps(row) + "\n")
One note on field names: normalize accepts id/video_id, views/play_count, and author/username. Confirm the exact keys against your installed client's output once, then keep the fallbacks so a schema change does not silently zero your metrics.
Representative output
Running with MIN_SAMPLE=5 against the 17 embedded example records prints one ranked JSON line per product (EXAMPLE output — your numbers will differ):
{"product": "pet hair remover", "videos": 5, "authors": 5, "median_views": 240000, "engagement_rate": 0.1083, "creator_breadth": 1.0, "recent_share": 1.0, "commercial_share": 0.2, "demand_score": 95.0, "verdict": "strong candidate"}
{"product": "portable blender", "videos": 5, "authors": 4, "median_views": 228000, "engagement_rate": 0.1006, "creator_breadth": 0.8, "recent_share": 0.8, "commercial_share": 0.4, "demand_score": 82.3, "verdict": "strong candidate"}
{"product": "sunset lamp", "videos": 4, "authors": 3, "median_views": 24500, "engagement_rate": 0.0676, "creator_breadth": 0.75, "recent_share": 0.75, "commercial_share": 0.0, "demand_score": 26.7, "verdict": "insufficient sample"}
{"product": "mini projector", "videos": 3, "authors": 3, "median_views": 15000, "engagement_rate": 0.0509, "creator_breadth": 1.0, "recent_share": 0.0, "commercial_share": 0.0, "demand_score": 15.0, "verdict": "insufficient sample"}
With the production default of MIN_SAMPLE=20, all four rows return insufficient sample instead. That is the correct behaviour on a 17-record sample, and it is the single most valuable line of code in the script: it stops a five-video impression from becoming a purchase order.
How to read the scorecard
pet hair remover leads at 95.0 — five videos from five different creators, a 240,000 median view count, an 10.8% median engagement rate, and every dated video inside the 30-day window. Broad creator base plus current activity is the pattern you want.
portable blender follows at 82.3 — nearly the same reach, but a 0.8 creator breadth (one account appears twice) and a 0.4 commercial share: two of five captions already carry buy-intent language. Not disqualifying, but the term is being actively monetized, so differentiation has to come from price, bundling, or creative rather than novelty.
sunset lamp at 26.7 — a quarter of the reach and roughly half the engagement of the leaders, with zero commercial captions. Either the term has no buying audience, or your query is too generic to find it. Both are reasons to look, not to buy.
mini projector at 15.0 — the recency share of 0.0 is decisive. Every dated video is older than 30 days, so the sample describes a past moment. Inventory bought against it arrives late.
Two mechanics to keep in mind. Min-max normalization is relative to the candidate set: adding a product shifts every other score, so compare products inside one run and compare runs by metrics rather than absolute score. And the weights are opinions, not physics — a business selling high-ticket items should raise engagement and lower volume.
For a broader treatment of turning public platform data into research inputs, the Chinese-language guide to collecting public TikTok content covers the workflow class and its constraints.
Pre-commit checklist
Before any inventory decision, confirm all seven:
- [ ] Each candidate term has at least 20 de-duplicated videos; anything less is unranked by design.
- [ ] The run happened twice, at least a week apart, and the direction is stable or improving.
- [ ] Creator breadth is above roughly 0.7 — the term is not three accounts talking to each other.
- [ ] Recency share is above 0.5 — at least half the content is from the last 30 days.
- [ ] You read the top 20 captions and comments manually; scoring finds candidates, it does not explain them.
- [ ] Commercial share is understood: high means validated demand and crowded supply.
- [ ] You checked the product against your supplier's actual lead time and minimum order quantity.
That last point kills more launches than bad research does.
Use cases
- Dropshipping shortlists. Score 30 terms weekly, keep the top five, then request supplier quotes.
- Private-label validation. Compare a generic term against a use-case term ("pet hair remover" versus "pet hair remover for car seats") to find the narrower wedge.
- Catalog pruning. Run the script on products you already sell; a collapsing recency share is a signal to cut reorder quantity.
- Creative briefing. The highest-engagement captions in your sample are a free hook library — extract their first three words and count frequency.
- Marketplace expansion. Re-run the same term in another language and check whether the pattern holds.
Build, buy, or borrow
| Option | Best for | Maintenance | Watch out for |
|---|---|---|---|
| Manual scrolling + notes | One product, one afternoon | None, not repeatable | Recency bias, no history |
| Spreadsheet + copy-paste | 3-5 products, occasional | Low | Transcript errors, no de-duplication |
| Repository-based collection (this workflow) | Weekly shortlists across 10+ terms | Moderate — re-verify output fields | You own normalization and scoring choices |
| Managed data provider | Large ongoing volumes, SLA needs | Low | Verify current coverage, pricing, and terms on the provider's official pages |
The scoring layer is identical in all four — one schema lets you swap the collection mechanism later without rewriting the analysis.
Limits, compliance, and maintenance
- This measures attention, not sales. No public metric tells you conversion rate, return rate, or margin. The score is a filter that reduces how many ideas you research properly.
- Samples are biased by design. Search results vary by region, language, account state, and time of day. Record query parameters and run date with every batch so later comparisons mean something.
- Public data only. Collect content visible without authentication. Do not touch private accounts, bypass access controls, or solve CAPTCHAs. Respect platform terms and robots directives.
- Personal data still applies. Creator handles and profile details can be personal data under regimes such as GDPR. Store the minimum, keep it secured, and honor deletion requests.
- Collection breaks before analysis does. Validate that each batch has a plausible record count and non-zero views before scoring, and alert on drops.
- Pace your requests. Use the rate limiting the repository documents, add conservative delays, and track error rates instead of pushing throughput.
- No guarantees. Re-read the README before production use and confirm current limits on official pages.
FAQ
Is this an official TikTok API?
No. These are open-source collection projects for public page data. TikTok does publish official APIs for specific partner and business use cases; check TikTok's developer documentation for current access requirements rather than assuming an open endpoint exists.
What is the minimum useful sample per product?
Twenty de-duplicated videos is a reasonable floor for a screening pass; 100+ makes the median and breadth figures far more stable. The script enforces the floor so a thin sample cannot masquerade as a ranking.
Does view count predict sales?
No. Views measure distribution; sales depend on price, offer, audience fit, and fulfilment. Use the scorecard to choose what to investigate, then validate with supplier quotes, ad tests, or pre-orders.
How often should I run it?
Weekly for four weeks gives you a direction instead of a snapshot. Monthly is enough for catalog pruning, where slow decay matters more than week-to-week noise.
What happens when the platform changes its layout?
Collection fails first: record counts drop, or view fields return zero. The normalization step tolerates alternate key names, but it cannot invent missing data — log raw record counts per run and compare with the previous one.
Can I feed the output into a sheet, a dashboard, or an AI agent?
Yes. Each line is self-contained JSON with the product, metrics, score, and verdict. Append runs to a dated JSONL file and keep the run date attached so any chart can be reproduced.
Do I need both repositories?
No. Either one collects the records this script needs. The API repository suits scheduled collection with downstream consumers; the video scraper suits ad-hoc exploration.
Next step
Clone the TikTok video scraper for per-video metrics, or the TikTok data scraper API with hashtag and profile endpoints if you want a service you can schedule — then run the script above on your own candidate list for two weeks before you commit inventory budget to anything.
More collection repositories across marketplaces, directories, and social platforms are listed on the data-scrape GitHub profile. Keep your weights and your sample floor versioned next to the script: the scoring decisions are yours, and they should be auditable a quarter later when someone asks why you bought that pallet.
Top comments (0)