1. Tutorials
  2. How to scrape TikTok Ad Library search
  3. Python

How to scrape TikTok Ad Library search with Python

A Python script that fetches TikTok Ad Library search, pages through the results and saves them to a file.

Get an API key; the examples use api.socialscrape.dev.

Set up

You need Python 3 and the requests package.

1python -m venv .venv2source .venv/bin/activate3pip install requests4export SOCIALSCRAPE_API_KEY=ss_live_...

The script

Save as scrape.py and run python scrape.py. It calls GET /v1/tiktok/ad-library/search.

1import csv2import os3import time45import requests67URL = "https://api.socialscrape.dev/v1/tiktok/ad-library/search"8HEADERS = {"x-api-key": os.environ["SOCIALSCRAPE_API_KEY"]}9PARAMS = {10    "query": "\"free trial\"",11    "start_date": "2026-10-22",12    "end_date": "2026-10-29",13}14MAX_ITEMS = 100151617def pick(obj, *path):18    """Follow a path through nested dicts; None if any step is missing or null."""19    for key in path:20        obj = obj.get(key) if isinstance(obj, dict) else None21    return obj222324def get(params):25    """One request. Failures cost nothing; retry the ones the API marks retryable."""26    for attempt in range(3):27        body = requests.get(URL, headers=HEADERS, params=params, timeout=60).json()28        if body["ok"]:29            return body30        err = body["error"]31        if not err["retryable"] or attempt == 2:32            raise RuntimeError(f'{err["code"]}: {err["message"]}')33        time.sleep(2**attempt)343536items = []37params = dict(PARAMS)38while len(items) < MAX_ITEMS:39    body = get(params)40    items += body["data"]["items"]41    if not body["has_more"]:42        break43    params["cursor"] = body["cursor"]44items = items[:MAX_ITEMS]4546with open("out.csv", "w", newline="", encoding="utf-8") as f:47    writer = csv.writer(f)48    writer.writerow(["title", "id"])49    for item in items:50        writer.writerow([pick(item, "title"), pick(item, "id")])5152print(f"saved {len(items)} rows to out.csv, credits left: {body['credits_remaining']}")

How it works

  1. get() sends one request and retries the failures the API marks retryable. A failed request costs nothing.
  2. The loop follows cursor until has_more is false or 100 items are collected. Each page costs its own price.
  3. pick() reads nested fields and gives None instead of crashing when the platform returned null.
  4. Rows go to out.csv, one column per field.

What you get back

These fields come from a recorded sample. The full field list is on the endpoint page.

SampleFields in the script
1{2  "title": "This year, sleep deeper, train smarter, and live better for longer. Start your WHOOP free trial.",3  "id": "1880321679899026"4}

The short version

Without paging, saving or retries, the request is this.

1import os2import requests34params = {5    "query": "\"free trial\"",6    "start_date": "2026-10-22",7    "end_date": "2026-10-29",8}9res = requests.get(10    "https://api.socialscrape.dev/v1/tiktok/ad-library/search",11    headers={"x-api-key": os.environ["SOCIALSCRAPE_API_KEY"]},12    params=params,13    timeout=60,14)15body = res.json()1617if body["ok"]:18    print(body["data"])19else:20    print(body["error"]["code"], body["error"]["message"])

With the SDK

The Python client does the retries and the paging for you: see the SDKs.

1from socialscrape import SocialScrape23client = SocialScrape()  # reads SOCIALSCRAPE_API_KEY45for item in client.paginate(client.tiktok.ad_library_search, query="\"free trial\"", start_date="2026-10-22", end_date="2026-10-29", max_items=100):6    print(item["title"])

What it costs

1 credit. A failed request costs nothing. Add max_age_days to reuse a cached result for 0 credits. Results are kept 30 days.

Next