# TikTok Scraper - Search, User Posts & Stories (`petrichors/tiktok-scraper`) Actor

Scrape TikTok videos by keyword search, or fetch all posts/stories from one or more usernames. No login required for search and public posts.

- **URL**: https://apify.com/petrichors/tiktok-scraper.md
- **Developed by:** [Muhamad Wildan](https://apify.com/petrichors) (community)
- **Categories:** Social media, Videos, Other
- **Stats:** 2 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.00005 / actor start

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are a software tools running on the Apify platform, for all kinds of web data extraction and automation use cases.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

In JavaScript/TypeScript projects, use official [JavaScript/TypeScript client](https://docs.apify.com/api/client/js/docs.md):

```bash
npm install apify-client
```

In Python projects, use official [Python client library](https://docs.apify.com/api/client/python/docs.md):

```bash
pip install apify-client
```

In shell scripts, use [Apify CLI](https://docs.apify.com/cli/docs.md):

````bash
# MacOS / Linux
curl -fsSL https://apify.com/install-cli.sh | bash
# Windows
irm https://apify.com/install-cli.ps1 | iex
```bash

In AI frameworks, you might use the [Apify MCP server](https://docs.apify.com/integrations/mcp.md).

If your project is in a different language, use the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).


# README

## TikTok Scraper (Search, User Posts & User Stories)

Scrape TikTok videos by keyword/hashtag search, or pull every post/story from
one or more usernames — no TikTok login required for search and public posts.

This Actor is an Apify wrapper around the `tiktok-end-to-end-crawler` engine:
the same async `TikTokAPI` client (pagination, retries, rate-limiting) that
already powers the original CLI tool / Kafka+Elasticsearch pipeline, just
re-pointed at the Apify dataset and Apify Proxy instead of Kafka/ES/argparse.

### Input

| Field | Type | Notes |
|---|---|---|
| `operation` | `search` \| `userPosts` \| `userStory` | What to scrape |
| `searchQuery` | string | Required for `search` |
| `usernames` | array of strings | Required for `userPosts` / `userStory`. Multiple usernames run in one job. |
| `resultsPerPage` | int (1-50) | Items requested per page, default 12 |
| `maxPagesPerQuery` | int | Pages to paginate per keyword/username, default 1 |
| `maxItems` | int | Hard stop for the whole run, default 50 (0 = unlimited) |
| `hd` | bool | Request HD video links, default true |
| `proxyConfiguration` | object | Apify Proxy — recommended, the upstream API rate-limits by IP |
| `cookies` | string (secret) | Only needed if `userPosts`/`userStory` return HTTP 403 |
| `rateLimitRps` | int | Requests/second cap for this run, default 5 |

### Output (one dataset row per video)

Each row is the full `TikTokPost` model (id, title, description, author,
music, video, stats, hashtags) plus a few flattened convenience fields:
`authorUsername`, `playUrlNoWatermark`, `playUrlWatermark`, `diggCount`,
`playCount`, `commentCount`, `shareCount`, `operation`, `queryValue`,
`scrapedAt`.

### What changed vs. the original CLI project

- **Dropped**: Kafka/Elasticsearch output drivers, the `Controllers`/`Input`/
  `Output` abstraction layer, env/YAML settings loading. Apify's dataset +
  input schema already cover that role, so keeping them would just add
  unused dependencies (slower builds = more compute cost on every run).
- **Kept as-is**: `TikTokAPI` (`tiktok_api.py`) and the Pydantic schemas
  (`schemas.py`) — same pagination/retry/backoff logic, same field
  aliases, same `model_dump(by_alias=True, exclude_none=True)` shape.
  `KafkaEvent` was renamed `ScrapeEvent` since there's no Kafka here.
- **Added**: Apify Proxy wiring (`proxy_url` was already a config field in
  the original `CrawlerSettings` — it just wasn't connected to anything
  before), and PPE charging via `Actor.push_data(item, charged_event_name=...)`.

### Monetizing this Actor

1. Push this folder to a GitHub repo (or use `apify push` from the Apify CLI).
2. In Apify Console → Actor → Monetization, set up **Pay per event (PPE)**
   and define an event named `post-scraped` (matches `CHARGED_EVENT_NAME` in
   `src/main.py`) — e.g. price it somewhere in the $1–10 per 1,000 results
   range, in line with typical Store pricing.
3. You don't need to touch the code further — `Actor.push_data(..., charged_event_name="post-scraped")`
   only actually charges once that event exists in Console; until then it's a no-op.

### Possible follow-ups (not built into v1, to keep the build light)

- Optional second output: also forward each item to your own Kafka topic or
  Elasticsearch index (you already have working drivers for both in the
  original project's `helpers/output/driver/`) — could be pitched as an
  "enterprise" / advanced-input toggle on top of the free dataset output.
- A 4th `postDetail` operation that re-uses `fetch_post()` to grab a single
  video by ID/URL.

# Actor input Schema

## `operation` (type: `string`):

What do you want to scrape?
## `searchQuery` (type: `string`):

Keyword or hashtag to search for. Required when Operation = "Search by keyword".
## `usernames` (type: `array`):

One or more TikTok usernames (with or without @). Required when Operation is "User posts" or "User stories".
## `resultsPerPage` (type: `integer`):

How many items to request per page from the API (1-50).
## `maxPagesPerQuery` (type: `integer`):

How many pages to paginate through for each keyword/username before moving to the next one.
## `maxItems` (type: `integer`):

Stop the whole run after this many items have been scraped across all queries. Set to 0 for no limit (use with caution on pay-per-event pricing).
## `hd` (type: `boolean`):

Ask the API for HD video URLs where available.
## `proxyConfiguration` (type: `object`):

Recommended: route requests through Apify Proxy to reduce rate-limiting from the upstream API.
## `cookies` (type: `string`):

Optional cookie string, e.g. "cf_clearance=...; current_language=en". Only needed if userPosts/userStory return HTTP 403.
## `rateLimitRps` (type: `integer`):

Maximum requests per second sent by this run. Lower it if you see frequent errors.

## Actor input object example

```json
{
  "operation": "search",
  "searchQuery": "persib",
  "usernames": [
    "@persib"
  ],
  "resultsPerPage": 12,
  "maxPagesPerQuery": 1,
  "maxItems": 50,
  "hd": true,
  "proxyConfiguration": {
    "useApifyProxy": true
  },
  "rateLimitRps": 5
}
````

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "searchQuery": "persib",
    "usernames": [
        "@persib"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("petrichors/tiktok-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "searchQuery": "persib",
    "usernames": ["@persib"],
}

# Run the Actor and wait for it to finish
run = client.actor("petrichors/tiktok-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "searchQuery": "persib",
  "usernames": [
    "@persib"
  ]
}' |
apify call petrichors/tiktok-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=petrichors/tiktok-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "TikTok Scraper - Search, User Posts & Stories",
        "description": "Scrape TikTok videos by keyword search, or fetch all posts/stories from one or more usernames. No login required for search and public posts.",
        "version": "0.1",
        "x-build-id": "QiNVZHL3VsoeJWAsU"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/petrichors~tiktok-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-petrichors-tiktok-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/petrichors~tiktok-scraper/runs": {
            "post": {
                "operationId": "runs-sync-petrichors-tiktok-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/petrichors~tiktok-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-petrichors-tiktok-scraper",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "operation"
                ],
                "properties": {
                    "operation": {
                        "title": "Operation",
                        "enum": [
                            "search",
                            "userPosts",
                            "userStory"
                        ],
                        "type": "string",
                        "description": "What do you want to scrape?",
                        "default": "search"
                    },
                    "searchQuery": {
                        "title": "Search keyword",
                        "type": "string",
                        "description": "Keyword or hashtag to search for. Required when Operation = \"Search by keyword\"."
                    },
                    "usernames": {
                        "title": "Usernames",
                        "type": "array",
                        "description": "One or more TikTok usernames (with or without @). Required when Operation is \"User posts\" or \"User stories\".",
                        "items": {
                            "type": "string"
                        }
                    },
                    "resultsPerPage": {
                        "title": "Results per page",
                        "minimum": 1,
                        "maximum": 50,
                        "type": "integer",
                        "description": "How many items to request per page from the API (1-50).",
                        "default": 12
                    },
                    "maxPagesPerQuery": {
                        "title": "Max pages per query",
                        "minimum": 1,
                        "type": "integer",
                        "description": "How many pages to paginate through for each keyword/username before moving to the next one.",
                        "default": 1
                    },
                    "maxItems": {
                        "title": "Max items total",
                        "minimum": 0,
                        "type": "integer",
                        "description": "Stop the whole run after this many items have been scraped across all queries. Set to 0 for no limit (use with caution on pay-per-event pricing).",
                        "default": 50
                    },
                    "hd": {
                        "title": "Request HD video links",
                        "type": "boolean",
                        "description": "Ask the API for HD video URLs where available.",
                        "default": true
                    },
                    "proxyConfiguration": {
                        "title": "Proxy configuration",
                        "type": "object",
                        "description": "Recommended: route requests through Apify Proxy to reduce rate-limiting from the upstream API.",
                        "default": {
                            "useApifyProxy": true
                        }
                    },
                    "cookies": {
                        "title": "Cookies (advanced)",
                        "type": "string",
                        "description": "Optional cookie string, e.g. \"cf_clearance=...; current_language=en\". Only needed if userPosts/userStory return HTTP 403."
                    },
                    "rateLimitRps": {
                        "title": "Rate limit (requests/second)",
                        "minimum": 1,
                        "maximum": 20,
                        "type": "integer",
                        "description": "Maximum requests per second sent by this run. Lower it if you see frequent errors.",
                        "default": 5
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
