# 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 web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — 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

Download the OpenAPI definition: https://api.apify.com/v2/actors/ptI1HJ9MKM0Dq6JkR/builds/QiNVZHL3VsoeJWAsU/openapi.json
