# TikTok Scraper — Profiles, Hashtags, Search & Videos (`api_heros/tiktok-scraper`) Actor

Scrape TikTok profiles, hashtags, search & video URLs. Returns enriched post, video and music metadata plus engagement stats, with optional media downloads.

- **URL**: https://apify.com/api\_heros/tiktok-scraper.md
- **Developed by:** [API HEROS](https://apify.com/api_heros) (community)
- **Categories:** Social media, Automation, Developer tools
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.001 / 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 Apify Actor

A production-ready Apify Actor for scraping TikTok profiles, hashtags, search results, and direct video URLs using Python, Playwright, Apify SDK, `aiohttp`, and Pydantic.

The Actor extracts structured TikTok data, supports optional media downloads to Apify Key-Value Store, uses proxy rotation and rate limiting, returns structured error items, and includes an MCP-compatible tool handler.

---

### Features

- Scrape TikTok profiles by username or profile URL
- Scrape hashtags by name or hashtag URL
- Scrape TikTok search results
- Scrape direct TikTok video URLs
- Scrape profile sections:
  - `videos`
  - `reposts`
  - `liked`
- Support profile sorting:
  - `latest`
  - `popular`
- Extract structured metadata:
  - video text
  - creation time
  - author metadata
  - music metadata
  - video metadata
  - hashtags
  - engagement stats
- Optional media downloads:
  - videos
  - covers
  - subtitles
  - avatars
- Store downloaded media in Apify Key-Value Store
- Inject public download URLs back into dataset items
- Structured error items for failed pages
- Apify Proxy integration
- Proxy rotation per browsing context
- Async Playwright scraping
- Anti-detection helpers
- Rate limiting and retry backoff
- MCP tool handler for external tool-based integrations
- Optional webhook trigger at the end of the run

---

### Project Structure

```text
tiktok-scraper/
├── .actor/
│   ├── actor.json
│   └── input_schema.json
├── src/
│   ├── main.py
│   ├── tiktok_scraper.py
│   ├── models.py
│   ├── utils.py
│   ├── rate_limiter.py
│   ├── media_downloader.py
│   └── mcp_handler.py
├── Dockerfile
├── requirements.txt
└── README.md
````

***

### Technology Stack

- Python 3.13
- Apify SDK for Python
- Playwright
- Chromium
- aiohttp
- Pydantic v2
- Docker
- Apify Platform

Base Docker image:

```text
apify/actor-python-playwright:3.13
```

***

### Installation

#### 1. Clone or create the project

```bash
mkdir -p tiktok-scraper/.actor tiktok-scraper/src
cd tiktok-scraper
```

Place all generated files into the matching paths.

#### 2. Install dependencies

```bash
pip install -r requirements.txt
```

#### 3. Install Playwright browsers

```bash
playwright install chromium
```

On some systems, you may also need:

```bash
playwright install-deps chromium
```

***

### Running Locally with Apify CLI

Install the Apify CLI:

```bash
npm install -g apify-cli
```

Login:

```bash
apify login
```

Run the Actor locally:

```bash
apify run
```

The Actor will use the local Apify storage directory by default.

***

### Running with Docker

Build the image:

apify\_api\_whqaEDGwEZwot7xT2TbfJrDzHc4e684fSzez

```bash
docker build -t tiktok-scraper .
```

Run the image:

```bash
docker run --rm \
  -e ACTOR_TOKEN=$ACTOR_TOKEN \
  tiktok-scraper
```

For full local development, using the Apify CLI is usually easier:

```bash
apify run
```

***

### Input Configuration

The Actor input is defined in:

```text
.actor/input_schema.json
```

#### Example Input

```json
{
  "profiles": [
    "@tiktok"
  ],
  "hashtags": [
    "fyp"
  ],
  "search": [
    "dance challenge",
    "user:comedian"
  ],
  "startUrls": [
    "https://www.tiktok.com/@tiktok/video/1234567890123456789"
  ],
  "resultsPerPage": 20,
  "profileScrapeSections": [
    "videos",
    "reposts",
    "liked"
  ],
  "profileSorting": "latest",
  "shouldDownloadVideos": false,
  "shouldDownloadCovers": false,
  "shouldDownloadSubtitles": false,
  "shouldDownloadAvatars": false,
  "excludePinnedPosts": false,
  "proxyCountryCode": "None",
  "maxProfilesPerQuery": 10,
  "maxConcurrency": 5,
  "maxRequestRetries": 3,
  "webhookUrl": null
}
```

***

### Input Fields

| Field | Type | Default | Description |
|---|---:|---:|---|
| `profiles` | `string[]` | `[]` | TikTok usernames or profile URLs. |
| `hashtags` | `string[]` | `[]` | Hashtag names or hashtag URLs. |
| `search` | `string[]` | `[]` | Search queries or TikTok search URLs. Use `user:query` to search profiles. |
| `startUrls` | `string[]` | `[]` | Direct TikTok URLs. |
| `resultsPerPage` | `integer` | `20` | Maximum number of items per scraping task. |
| `profileScrapeSections` | `string[]` | `["videos"]` | Profile tabs to scrape: `videos`, `reposts`, `liked`. |
| `profileSorting` | `string` | `latest` | Profile sorting: `latest` or `popular`. |
| `shouldDownloadVideos` | `boolean` | `false` | Download videos to Key-Value Store. |
| `shouldDownloadCovers` | `boolean` | `false` | Download cover images. |
| `shouldDownloadSubtitles` | `boolean` | `false` | Download subtitle files when available. |
| `shouldDownloadAvatars` | `boolean` | `false` | Download author avatars. |
| `excludePinnedPosts` | `boolean` | `false` | Exclude pinned posts from profile results. |
| `proxyCountryCode` | `string` | `"None"` | Apify Proxy country code. Use `"None"` for no country preference. |
| `maxProfilesPerQuery` | `integer` | `10` | Maximum profiles scraped from a profile search query. |
| `maxConcurrency` | `integer` | `5` | Maximum concurrent media downloads and internal operations. |
| `maxRequestRetries` | `integer` | `3` | Maximum navigation retries. |
| `webhookUrl` | `string \| null` | `null` | Optional webhook URL triggered at the end of the run. |

***

### Profile Input Examples

Username:

```json
{
  "profiles": ["@tiktok"]
}
```

Without `@`:

```json
{
  "profiles": ["tiktok"]
}
```

Profile URL:

```json
{
  "profiles": ["https://www.tiktok.com/@tiktok"]
}
```

Profile liked videos:

```json
{
  "profiles": ["https://www.tiktok.com/@tiktok/liked"]
}
```

Multiple profile sections:

```json
{
  "profiles": ["@tiktok"],
  "profileScrapeSections": ["videos", "reposts", "liked"]
}
```

***

### Hashtag Input Examples

Hashtag name:

```json
{
  "hashtags": ["fyp"]
}
```

With `#`:

```json
{
  "hashtags": ["#fyp"]
}
```

Hashtag URL:

```json
{
  "hashtags": ["https://www.tiktok.com/tag/fyp"]
}
```

***

### Search Input Examples

Normal video search:

```json
{
  "search": ["dance challenge"]
}
```

Profile search:

```json
{
  "search": ["user:comedian"]
}
```

Direct TikTok search URL:

```json
{
  "search": ["https://www.tiktok.com/search?q=dance"]
}
```

Direct TikTok user search URL:

```json
{
  "search": ["https://www.tiktok.com/search/user?q=comedian"]
}
```

When using profile search, the Actor collects up to `maxProfilesPerQuery` profile URLs and scrapes them.

***

### Start URL Examples

Video URL:

```json
{
  "startUrls": [
    "https://www.tiktok.com/@username/video/1234567890123456789"
  ]
}
```

Profile URL:

```json
{
  "startUrls": [
    "https://www.tiktok.com/@username"
  ]
}
```

Hashtag URL:

```json
{
  "startUrls": [
    "https://www.tiktok.com/tag/fyp"
  ]
}
```

Search URL:

```json
{
  "startUrls": [
    "https://www.tiktok.com/search?q=dance"
  ]
}
```

***

### Output Dataset

Successful items are pushed to the default Apify dataset.

#### Example Output Item

```json
{
  "id": "1234567890123456789",
  "text": "Example video description #fyp",
  "textLanguage": "en",
  "createTimeISO": "2026-01-01T12:00:00+00:00",
  "isAd": false,
  "isPinned": false,
  "authorMeta": {
    "id": "1234567890",
    "name": "username",
    "profileUrl": "https://www.tiktok.com/@username",
    "nickName": "User Name",
    "verified": false,
    "signature": "Example bio",
    "bioLink": "https://example.com",
    "avatar": "https://example.com/avatar.jpg",
    "fans": 100000,
    "following": 100,
    "heart": 5000000,
    "video": 250
  },
  "musicMeta": {
    "musicName": "Original Sound",
    "musicAuthor": "username",
    "musicOriginal": true,
    "playUrl": "https://example.com/music.mp3",
    "musicId": "987654321"
  },
  "videoMeta": {
    "height": 1024,
    "width": 576,
    "duration": 15,
    "coverUrl": "https://example.com/cover.jpg",
    "originalCoverUrl": "https://example.com/original-cover.jpg",
    "definition": "720p",
    "format": "mp4",
    "subtitleLinks": [],
    "playUrl": "https://example.com/video.mp4"
  },
  "diggCount": 1000,
  "shareCount": 200,
  "playCount": 50000,
  "collectCount": 300,
  "commentCount": 150,
  "hashtags": [
    {
      "id": "123",
      "name": "fyp",
      "title": "fyp"
    }
  ],
  "webVideoUrl": "https://www.tiktok.com/@username/video/1234567890123456789",
  "input": "@username",
  "searchQuery": null
}
```

***

### Downloaded Media Fields

When media downloads are enabled, the Actor adds download URLs back into the dataset item.

#### Video Download

Enabled by:

```json
{
  "shouldDownloadVideos": true
}
```

Added field:

```json
{
  "videoMeta": {
    "downloadedUrl": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/videos/example-video.mp4"
  }
}
```

#### Cover Download

Enabled by:

```json
{
  "shouldDownloadCovers": true
}
```

Added field:

```json
{
  "videoMeta": {
    "downloadedCoverUrl": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/covers/example-cover.jpg"
  }
}
```

#### Avatar Download

Enabled by:

```json
{
  "shouldDownloadAvatars": true
}
```

Added field:

```json
{
  "authorMeta": {
    "downloadedAvatarUrl": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/avatars/example-avatar.jpg"
  }
}
```

#### Subtitle Download

Enabled by:

```json
{
  "shouldDownloadSubtitles": true
}
```

Added field:

```json
{
  "videoMeta": {
    "downloadedSubtitleLinks": [
      {
        "originalUrl": "https://example.com/subtitle.vtt",
        "downloadedUrl": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/subtitles/example-subtitle.vtt",
        "language": "en"
      }
    ]
  }
}
```

***

### Error Items

If scraping fails, the Actor pushes a structured error item to the dataset.

#### Example Error Item

```json
{
  "url": "https://www.tiktok.com/@privateuser",
  "input": "@privateuser",
  "error": "The profile is private.",
  "errorCode": "PROFILE_PRIVATE"
}
```

***

### Error Codes

| Error Code | Meaning |
|---|---|
| `NOT_FOUND` | The requested page or entity was not found. |
| `POST_NOT_FOUND_OR_PRIVATE` | The post is not found, private, or deleted. |
| `PROFILE_PRIVATE` | The profile is private. |
| `PROFILE_EMPTY` | The profile has no public posts. |
| `SEARCH_QUERY_NOT_FOUND` | The search query did not return results. |
| `INVALID_URLS` | The URL is invalid or unsupported. |
| `CAPTCHA_CHALLENGE` | TikTok presented a captcha challenge. |
| `UNKNOWN_ERROR` | An unexpected scraping error occurred. |

***

### Proxy Configuration

The Actor supports Apify Proxy.

By default, it attempts to create a proxy configuration using:

```json
{
  "proxyCountryCode": "None"
}
```

To prefer a specific country:

```json
{
  "proxyCountryCode": "US"
}
```

The Actor creates a new proxy context per scraping task when proxy configuration is available.

***

### Rate Limiting

The Actor includes an asynchronous rate limiter with:

- minimum delay between requests
- randomized delay
- error backoff
- concurrency control

Default rate limiter settings in `src/main.py`:

```python
AsyncRateLimiter(
    min_delay=1.2,
    max_delay=2.8,
    max_concurrency=input_model.maxConcurrency,
)
```

You can adjust these values if needed.

***

### Pay-Per-Event Pricing

The Actor includes Pay-Per-Event pricing placeholders in:

```text
.actor/actor.json
```

Configured events:

| Event Name | Description |
|---|---|
| `scrape_profile_result` | Charged for each successfully scraped result item. |
| `download_video` | Charged for each successfully downloaded video. |

Example pricing placeholder:

```json
{
  "pricingModel": "PAY_PER_EVENT",
  "pricing": {
    "payPerEvent": {
      "scrape_profile_result": {
        "title": "Scraped TikTok result item",
        "unitPrice": 0.0005
      },
      "download_video": {
        "title": "Downloaded TikTok video",
        "unitPrice": 0.001
      }
    }
  }
}
```

Adjust pricing values before publishing.

***

### Webhook Support

You can provide an optional `webhookUrl` in the input.

```json
{
  "webhookUrl": "https://example.com/webhook"
}
```

At the end of the run, the Actor sends a `POST` request with a payload similar to:

```json
{
  "eventType": "ACTOR.RUN.SUCCEEDED",
  "actorRunId": "RUN_ID",
  "datasetId": "DATASET_ID",
  "keyValueStoreId": "KEY_VALUE_STORE_ID",
  "items": 20,
  "errors": 1,
  "downloads": 5,
  "finishedAt": "2026-07-21T12:00:00+00:00"
}
```

***

### Apify API Usage

After deploying the Actor to Apify, it can be started through the Apify REST API.

Example:

```bash
curl -X POST \
  "https://api.apify.com/v2/acts/YOUR_USERNAME~tiktok-scraper/runs?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "profiles": ["@tiktok"],
    "resultsPerPage": 10
  }'
```

Replace:

- `YOUR_USERNAME` with your Apify username
- `YOUR_APIFY_TOKEN` with your Apify API token
- `tiktok-scraper` with your Actor name if different

***

### MCP Integration

The file `src/mcp_handler.py` includes an MCP-compatible handler.

Available tools:

```text
scrape_tiktok_profile
scrape_tiktok_hashtag
scrape_tiktok_search
scrape_tiktok_url
```

#### Example MCP JSON-RPC Request

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "scrape_tiktok_profile",
    "arguments": {
      "profile": "@tiktok",
      "resultsPerPage": 5
    }
  }
}
```

#### Example Python Usage

```python
import asyncio

from mcp_handler import MCPHandler


async def main():
    handler = MCPHandler()

    response = await handler.handle_jsonrpc(
        {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": "scrape_tiktok_profile",
                "arguments": {
                    "profile": "@tiktok",
                    "resultsPerPage": 5,
                },
            },
        }
    )

    print(response)


asyncio.run(main())
```

***

### Output Stored in Key-Value Store

The Actor stores a run summary in the default Key-Value Store under:

```text
OUTPUT
```

Example:

```json
{
  "finishedAt": "2026-07-21T12:00:00+00:00",
  "items": 20,
  "errors": 1,
  "downloads": 5,
  "datasetId": "DATASET_ID",
  "keyValueStoreId": "KEY_VALUE_STORE_ID",
  "actorRunId": "RUN_ID"
}
```

Downloaded media files are also stored in the default Key-Value Store under prefixes:

```text
videos/
covers/
avatars/
subtitles/
```

***

### Anti-Detection

The Actor uses several anti-detection helpers:

- hides `navigator.webdriver`
- sets realistic browser headers
- sets realistic viewport and locale
- injects stealth initialization scripts
- uses randomized delays
- rotates proxy contexts when Apify Proxy is available
- dismisses common modal overlays where possible

TikTok may still present captchas, login walls, or temporary blocks.

***

### Limitations

TikTok uses aggressive anti-scraping protections. Scraping results may vary depending on:

- IP quality
- proxy country
- TikTok UI changes
- embedded JSON structure changes
- account visibility
- region restrictions
- captcha challenges
- login requirements
- rate limits

Private profiles, deleted videos, unavailable hashtags, and captcha walls may produce structured error items.

***

### Troubleshooting

#### `CAPTCHA_CHALLENGE`

TikTok requires captcha verification.

Possible fixes:

- use better proxies
- reduce request volume
- change proxy country
- retry later
- use residential proxies if available

#### `PROFILE_PRIVATE`

The profile is private.

No public data can be extracted.

#### `PROFILE_EMPTY`

The profile exists but no public posts were found.

Possible causes:

- empty profile
- region restriction
- TikTok UI change
- scraping was blocked

#### `SEARCH_QUERY_NOT_FOUND`

The search query returned no extractable results.

Possible fixes:

- try a different query
- check whether TikTok search requires login
- use a different proxy country

#### `INVALID_URLS`

The URL is not a supported TikTok URL.

Supported examples:

```text
https://www.tiktok.com/@username
https://www.tiktok.com/@username/video/123
https://www.tiktok.com/tag/fyp
https://www.tiktok.com/search?q=dance
```

***

### Development

#### File Responsibilities

| File | Responsibility |
|---|---|
| `src/main.py` | Apify Actor entry point. |
| `src/tiktok_scraper.py` | Core Playwright scraping logic. |
| `src/models.py` | Pydantic input and output models. |
| `src/utils.py` | URL normalization, parsing, embedded state extraction, error mapping. |
| `src/rate_limiter.py` | Async rate limiting and backoff. |
| `src/media_downloader.py` | Media downloading to Key-Value Store. |
| `src/mcp_handler.py` | MCP tool handling and JSON-RPC routing. |

***

### Local Testing Example

Create an input file:

```bash
cat > input.json <<'EOF'
{
  "profiles": ["@tiktok"],
  "resultsPerPage": 5,
  "shouldDownloadVideos": false,
  "shouldDownloadCovers": false,
  "shouldDownloadSubtitles": false,
  "shouldDownloadAvatars": false
}
EOF
```

Run with Apify CLI:

```bash
apify run
```

Check local storage:

```text
storage/
```

***

### Docker Build

```bash
docker build -t tiktok-scraper .
```

***

### Compliance Notice

Use this Actor responsibly.

Before scraping TikTok, make sure you comply with:

- TikTok Terms of Service
- applicable privacy laws
- data protection regulations
- platform rate limits
- intellectual property rules
- local legal requirements

Do not use this Actor to collect private data without authorization or to violate platform policies.

***

### License

Adjust this section according to your project needs.

Example:

```text
MIT License
```

````

# Actor input Schema

## `hashtags` (type: `array`):

Hashtag names or URLs to scrape.
## `profiles` (type: `array`):

TikTok usernames or profile URLs to scrape.
## `search` (type: `array`):

Search queries or TikTok search URLs. Prefix with user: to search profiles.
## `startUrls` (type: `array`):

Direct TikTok URLs to scrape.
## `resultsPerPage` (type: `integer`):

Maximum number of result items per scraping task.
## `profileScrapeSections` (type: `array`):

Profile tabs to scrape. Allowed values: videos, reposts, liked.
## `profileSorting` (type: `string`):

Sorting for profile video lists.
## `shouldDownloadVideos` (type: `boolean`):

Download video files to the key-value store and add a downloadedUrl to each item.
## `shouldDownloadCovers` (type: `boolean`):

Download cover images to the key-value store.
## `shouldDownloadSubtitles` (type: `boolean`):

Download subtitle/caption files (when available) to the key-value store.
## `shouldDownloadAvatars` (type: `boolean`):

Download author avatar images to the key-value store.
## `excludePinnedPosts` (type: `boolean`):

Skip pinned posts when scraping profiles.
## `proxyCountryCode` (type: `string`):

Country code for Apify Proxy, or None.
## `maxProfilesPerQuery` (type: `integer`):

Maximum number of profiles scraped from a profile search query.
## `maxConcurrency` (type: `integer`):

Maximum concurrent media downloads and internal operations.
## `maxRequestRetries` (type: `integer`):

Maximum retries for navigation requests.
## `webhookUrl` (type: `string`):

Optional URL triggered at the end of the run. Leave empty to disable.

## Actor input object example

```json
{
  "hashtags": [],
  "profiles": [],
  "search": [],
  "startUrls": [],
  "resultsPerPage": 20,
  "profileScrapeSections": [
    "videos"
  ],
  "profileSorting": "latest",
  "shouldDownloadVideos": false,
  "shouldDownloadCovers": false,
  "shouldDownloadSubtitles": false,
  "shouldDownloadAvatars": false,
  "excludePinnedPosts": false,
  "proxyCountryCode": "None",
  "maxProfilesPerQuery": 10,
  "maxConcurrency": 5,
  "maxRequestRetries": 3,
  "webhookUrl": ""
}
````

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("api_heros/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 = {}

# Run the Actor and wait for it to finish
run = client.actor("api_heros/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 '{}' |
apify call api_heros/tiktok-scraper --silent --output-dataset

```

## MCP server setup

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

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "TikTok Scraper — Profiles, Hashtags, Search & Videos",
        "description": "Scrape TikTok profiles, hashtags, search & video URLs. Returns enriched post, video and music metadata plus engagement stats, with optional media downloads.",
        "version": "0.1",
        "x-build-id": "8gXipFyeMpAnit5b3"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/api_heros~tiktok-scraper/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-api_heros-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/api_heros~tiktok-scraper/runs": {
            "post": {
                "operationId": "runs-sync-api_heros-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/api_heros~tiktok-scraper/run-sync": {
            "post": {
                "operationId": "run-sync-api_heros-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",
                "properties": {
                    "hashtags": {
                        "title": "Hashtags",
                        "type": "array",
                        "description": "Hashtag names or URLs to scrape.",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "profiles": {
                        "title": "Profiles",
                        "type": "array",
                        "description": "TikTok usernames or profile URLs to scrape.",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "search": {
                        "title": "Search queries",
                        "type": "array",
                        "description": "Search queries or TikTok search URLs. Prefix with user: to search profiles.",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "startUrls": {
                        "title": "Start URLs",
                        "type": "array",
                        "description": "Direct TikTok URLs to scrape.",
                        "items": {
                            "type": "string"
                        },
                        "default": []
                    },
                    "resultsPerPage": {
                        "title": "Results per page",
                        "minimum": 1,
                        "maximum": 1000,
                        "type": "integer",
                        "description": "Maximum number of result items per scraping task.",
                        "default": 20
                    },
                    "profileScrapeSections": {
                        "title": "Profile sections",
                        "type": "array",
                        "description": "Profile tabs to scrape. Allowed values: videos, reposts, liked.",
                        "items": {
                            "type": "string"
                        },
                        "default": [
                            "videos"
                        ]
                    },
                    "profileSorting": {
                        "title": "Profile sorting",
                        "enum": [
                            "latest",
                            "popular"
                        ],
                        "type": "string",
                        "description": "Sorting for profile video lists.",
                        "default": "latest"
                    },
                    "shouldDownloadVideos": {
                        "title": "Download videos",
                        "type": "boolean",
                        "description": "Download video files to the key-value store and add a downloadedUrl to each item.",
                        "default": false
                    },
                    "shouldDownloadCovers": {
                        "title": "Download covers",
                        "type": "boolean",
                        "description": "Download cover images to the key-value store.",
                        "default": false
                    },
                    "shouldDownloadSubtitles": {
                        "title": "Download subtitles",
                        "type": "boolean",
                        "description": "Download subtitle/caption files (when available) to the key-value store.",
                        "default": false
                    },
                    "shouldDownloadAvatars": {
                        "title": "Download avatars",
                        "type": "boolean",
                        "description": "Download author avatar images to the key-value store.",
                        "default": false
                    },
                    "excludePinnedPosts": {
                        "title": "Exclude pinned posts",
                        "type": "boolean",
                        "description": "Skip pinned posts when scraping profiles.",
                        "default": false
                    },
                    "proxyCountryCode": {
                        "title": "Proxy country code",
                        "type": "string",
                        "description": "Country code for Apify Proxy, or None.",
                        "default": "None"
                    },
                    "maxProfilesPerQuery": {
                        "title": "Max profiles per query",
                        "minimum": 1,
                        "maximum": 1000,
                        "type": "integer",
                        "description": "Maximum number of profiles scraped from a profile search query.",
                        "default": 10
                    },
                    "maxConcurrency": {
                        "title": "Max concurrency",
                        "minimum": 1,
                        "maximum": 50,
                        "type": "integer",
                        "description": "Maximum concurrent media downloads and internal operations.",
                        "default": 5
                    },
                    "maxRequestRetries": {
                        "title": "Max request retries",
                        "minimum": 1,
                        "maximum": 10,
                        "type": "integer",
                        "description": "Maximum retries for navigation requests.",
                        "default": 3
                    },
                    "webhookUrl": {
                        "title": "Webhook URL",
                        "type": "string",
                        "description": "Optional URL triggered at the end of the run. Leave empty to disable.",
                        "default": ""
                    }
                }
            },
            "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
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
