# YouTube Trending Scraper (`scrapemamba/youtube-trending-scraper`) Actor

Get YouTube trending videos by country — optional Music, Gaming, Movies, or Now shelves. Point-in-time chart snapshots as Dataset rows for market pulse research.

- **URL**: https://apify.com/scrapemamba/youtube-trending-scraper.md
- **Developed by:** [Scrape Mamba](https://apify.com/scrapemamba) (community)
- **Categories:**
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.70 / 1,000 results

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/actors/running/actors-in-store.md#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

## YouTube Trending Scraper

Capture a point-in-time snapshot of **YouTube trending videos** for any supported country — and optionally a Music, Gaming, Movies, or Now shelf — as structured Dataset rows you can schedule, export, and join to the rest of your enrichment stack.

Built by **ScrapeMamba** for [Apify](https://apify.com). This **apify youtube scraper** is the chart-pulse **youtube scraper** in the suite: open **[YouTube Trending Scraper](https://apify.com/scrapemamba/youtube-trending-scraper)**, pick a country (default `US`), optionally choose a section and UI language, and cap how many videos you keep from the **first trending page**. **Trending on YouTube** moves fast — every run is a snapshot, not a historical archive. If you need to **scrape YouTube** charts without babysitting browsers, this Actor is the lightest-cost entry point before deeper **youtube scraping** (metadata, related graphs, or transcripts).

This Actor is the cheapest entry in the ScrapeMamba YouTube suite on Apify (**$1.70 per 1,000 results**). Use it when you want a pulse on what is rising in a market before you spend more on video details or captions.

***

### Overview

YouTube’s Trending surface is a curated, region-sensitive chart. Marketers, researchers, and data teams often want **YouTube trending videos** in a warehouse — not in a browser tab — so they can:

- Diff daily or hourly chart membership by country
- Seed competitor and creator watchlists from what is trending on YouTube right now
- Feed downstream scrapers with fresh, high-signal video IDs

**YouTube Trending Scraper** calls ScrapeMamba’s `/youtube/trending` endpoint with your `country`, optional `lang`, and optional `section`. The Actor maps listing items into a stable video schema (`videoId`, `title`, `author`, `channelId`, `views`, `length`, `publishedTime`, `thumbnail`, `url`, and more), tags each row with the `country` and `section` you requested, and pushes them to the Apify Dataset.

Important behavioral facts (accurate to this Actor’s code):

- **All input fields are optional.** Defaults: `country = US`, `maxResults = 50`.
- **First page only.** Continuation tokens are ignored; a second page fetch returns an empty payload by design. Raising `maxResults` only keeps more items from that single first-page response (capped 1–500).
- **No worker pool.** One country (and one section) is fetched per run — there is no multi-country fan-out inside a single Actor start.
- **Strict failure mode.** If the trending fetch throws, the Actor pushes a `type: "error"` row, then exits with **exit code 1**.

Public YouTube data only. Private, region-blocked, or otherwise unavailable surfaces may produce empty charts or error rows.

***

### Who this is not for

- **Media downloaders** — extracts chart **metadata**, not video/audio files.
- **Historical ranking archives** — charts change fast; store your own run timestamps and diffs.
- **Personalized Trending** — public surface only.

***

### What it does

- Fetches the trending listing for an ISO country code (default `US`)
- Optionally targets a shelf via `section`: `Now`, `Music`, `Gaming`, or `Movies`
- Optionally passes a UI `lang` (for example `en`) when you want language-biased presentation
- Caps how many mapped videos to keep with `maxResults` (default `"50"`, range 1–500)
- Writes `type: "video"` rows (and `type: "error"` on hard failure)
- Leaves `section` as `null` in the Dataset when you did not set a section

***

### Why ScrapeMamba on Apify

Trending pages are HTML- and Innertube-heavy. Building and babysitting your own browser farm for a daily chart scrape is usually more expensive than the chart is worth. ScrapeMamba’s backend handles the fetch; this Apify Actor handles input validation, field mapping, Dataset persistence, schedules, and exports — the same operational model as the rest of the suite’s **youtube scraper** Actors.

You get a fixed schema for BI joins on `videoId`, Dataset export, schedules/webhooks, handoff into Search / Video / Channel Scrapers, and a **youtube scraper api** path via Apify Client.

If you already discover keywords with Search Scraper, Trending is the complementary “what the platform is pushing right now” feed.

***

### Use cases

#### 1. Daily market pulse

Schedule the Actor for `country: "US"` (or your primary market) every morning. Store Dataset snapshots by run ID or append `fetchedAt` in your warehouse ETL. Diff `videoId` sets day over day to see what entered, left, or stuck on the chart of **YouTube trending videos**.

#### 2. Vertical shelf monitoring

Set `section` to `Music`, `Gaming`, or `Movies` when you care about a vertical, not the general Now chart. Run separate schedules per section if you need parallel coverage — this Actor does one section per run.

#### 3. Seed lists for enrichment

Take trending `videoId` values and pipe them into **YouTube Video Scraper** for fuller metadata (description, likes when exposed, microformat dates). Optionally resolve uploaders with **YouTube Channel Scraper**.

#### 4. Competitive and culture research

Compare the same section across countries (for example `US` vs `IN` vs `GB`) with separate runs. Because charts are snapshots of what is **trending on YouTube**, keep timestamps; do not assume yesterday’s Gaming shelf still looks like today’s.

#### 5. Lightweight alerting

Webhook a schedule when a competitor `channelId` appears on today’s shelf.

#### 6. Catalog seeding

Pull top N trending URLs into a CMS draft queue with a low `maxResults` (10–20).

***

### Pricing

- **$1.70 per 1,000 results** (cheapest in the ScrapeMamba YouTube suite on Apify)

You pay for Dataset rows from the run. Validate Input before scheduling aggressively so failed runs do not burn compute.

***

### Input

All fields are optional.

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `country` | string | No | `US` | ISO 3166-1 alpha-2 country code (normalized to uppercase). Invalid codes fall back to `US`. |
| `lang` | string | No | — | Optional UI language (for example `en`). Empty/blank values are omitted from the API body. |
| `section` | string (select) | No | — | Trending shelf: `Now`, `Music`, `Gaming`, or `Movies`. When unset, `section` on output rows is `null`. |
| `maxResults` | string / number | No | `"50"` | Maximum videos to keep from the **first** trending page. Clamped to **1–500**. |

#### Input JSON examples

Default US chart, first 50 videos:

```json
{}
```

Music shelf in India, English UI, top 30:

```json
{
  "country": "IN",
  "lang": "en",
  "section": "Music",
  "maxResults": "30"
}
```

Gaming shelf, United Kingdom:

```json
{
  "country": "GB",
  "section": "Gaming",
  "maxResults": "50"
}
```

***

### Output

#### Row types

| `type` | When | Notes |
|--------|------|-------|
| `video` | Successful mapped listing item with a `videoId` | Includes `country`, `section` (`null` if unset), `page`, mapped fields, and `raw` |
| `error` | Hard failure of the trending fetch | Includes `country`, `section`, and `error` string; Actor then **exits with code 1** |

#### Video field reference

| Field | Description |
|-------|-------------|
| `type` | Always `"video"` for success rows |
| `country` | Normalized country used for the request (for example `US`) |
| `section` | Shelf you selected, or `null` |
| `page` | Listing page index (effectively `1` — first page only) |
| `videoId` | Canonical 11-character YouTube ID |
| `title` | Video title when present on the listing |
| `author` | Channel display name when present |
| `channelId` | Uploader `UC…` ID when the listing exposes it |
| `views` | View count text or number as returned by the listing |
| `length` | Duration text when available |
| `publishedTime` | Relative or absolute publish string when present |
| `description` | Short description / snippet when present (may be truncated in mapping) |
| `thumbnail` | Best available thumbnail URL |
| `url` | Watch or Shorts URL derived from `videoId` |
| `isShort` | Boolean hint when the listing looks like a Short |
| `raw` | Underlying renderer / payload fragment for debugging |

Items without a resolvable `videoId` are skipped and never pushed.

#### Example video row

```json
{
  "type": "video",
  "country": "US",
  "section": "Music",
  "page": 1,
  "videoId": "dQw4w9WgXcQ",
  "title": "Example Trending Track",
  "author": "Example Artist",
  "channelId": "UCuAXFkgsw1L7xaCfnd5JJOw",
  "views": "1.2M views",
  "length": "3:32",
  "publishedTime": "2 days ago",
  "thumbnail": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",
  "url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  "isShort": false
}
```

#### Example error row

```json
{
  "type": "error",
  "country": "US",
  "section": null,
  "error": "HTTP 500: Upstream fetch failed. ..."
}
```

***

### Backend endpoint

The Actor POSTs to ScrapeMamba:

```
POST /youtube/trending
```

Request body fields (only non-empty values are sent):

| API field | Source |
|-----------|--------|
| `country` | Input `country` (default `US`) |
| `lang` | Input `lang` when set |
| `section` | Input `section` when set |

The HTTP client retries on `429`, `500`, `502`, `503`, and `504` (up to 3 attempts with backoff).

**Pagination note:** Even though the shared helper can walk continuations for other Actors, this trending Actor’s `fetchPage` returns `{}` whenever a continuation token is present. Practically: **first page only**.

***

### How to run on Apify (walkthrough)

1. Open **[YouTube Trending Scraper](https://apify.com/scrapemamba/youtube-trending-scraper)** on Apify.
2. Click **Start** (or **Try for free**).
3. Leave Input empty for a default US chart of up to 50 videos, or set `country` / `section` / `lang` / `maxResults`.
4. Wait for the run to finish. Open the **Dataset** tab and confirm `type: "video"` rows.
5. Export JSON/CSV/Excel, or pull rows via the Apify API / client SDKs.
6. For production pulse checks, create an Apify **Schedule** (for example daily at 09:00 in your timezone) and optionally a webhook to your ETL.

#### Quick start checklist

1. One public country with a known Trending surface (start with `US`)
2. Confirm Dataset columns (`videoId`, `title`, `country`)
3. Add `section` only after the default shelf looks right
4. Schedule once you accept that charts are snapshots

***

### Apify API example

Start a run with the Apify API:

```bash
curl "https://api.apify.com/v2/acts/scrapemamba~youtube-trending-scraper/runs" \
  -H "Content-Type: application/json" \
  -d '{
    "country": "US",
    "section": "Gaming",
    "lang": "en",
    "maxResults": "40"
  }'
```

Node.js sketch with the Apify client:

```js
import { ApifyClient } from 'apify-client';

const client = new ApifyClient();
const run = await client.actor('scrapemamba/youtube-trending-scraper').call({
  country: 'US',
  section: 'Music',
  maxResults: '50',
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items.filter((row) => row.type === 'video').length);
```

***

### Errors and exit behavior

On trending fetch failure the Actor logs, pushes `{ type: "error", country, section, error }`, then `Actor.exit({ exitCode: 1 })`. Schedules/CI can treat non-zero exit as hard failure. An empty-but-successful chart (zero mapped videos) does **not** force exit code 1.

Common errors: HTTP `429`/`5xx` after retries, `API returned success=false`, 60s request timeout.

***

### Best practices

1. **Treat results as snapshots** — store run time with every `videoId` list.
2. **Start with defaults** (`US`, empty Input) before adding sections.
3. **One country/section per run** — fan out with parallel Actor starts for multi-market coverage.
4. **Keep `maxResults` realistic** — first page only; `500` will not invent page two.
5. **Enrich listing stats** with Video Scraper when you need cleaner numeric fields.
6. **Schedule to freshness needs** — hourly for hot markets, daily when enough.
7. **Public data only.**

***

### Limitations

- **First trending page only** — no continuation crawl
- **Shelf availability varies** by country and `section`
- **Charts change quickly** — never treat a Dataset as durable ranking history without your own timestamps
- **Listing metadata is thinner** than full `video_details` payloads
- **Public data only**
- **Single-country fetch per run**

***

### Troubleshooting

| Symptom | Likely cause | What to try |
|---------|--------------|-------------|
| Run fails immediately, exit code 1 | Upstream fetch failed | Inspect the Dataset `type: "error"` row and Actor logs; retry |
| Zero video rows, run succeeded | Empty/unmapped shelf for that country/section | Try `US` without `section`; inspect logs |
| Fewer rows than `maxResults` | First page simply has fewer items | Expected; lower the cap or accept the page size |
| Want page 2+ of trending | Not supported | Use Search / Channel Videos for broader catalogs |
| Relative view strings hard to chart | Listing format | Enrich IDs with Video Scraper |
| Need many countries | Single fetch design | Parallel Actor runs per country |

***

### FAQ

#### How to get YouTube trending videos by country?

Set Input `country` to an ISO 3166-1 alpha-2 code (`US`, `IN`, `GB`, `DE`, `BR`, …). Leave `section` empty for the default national chart, or set `Music` / `Gaming` / `Movies` / `Now`. Dataset rows include the normalized `country`. Need several markets? Launch **one run per country** (or an Apify task matrix) — no multi-country fan-out in a single start. That is how to get **YouTube trending videos** for a region as a snapshot.

#### Does this scrape more than the first trending page?

No. The Actor intentionally stops after the first page. `maxResults` only caps how many first-page items you keep (1–500).

#### Are all inputs optional?

Yes. Defaults are `country: US` and `maxResults: 50`. `lang` and `section` are omitted unless you set them.

#### What happens if I leave `section` empty?

The Actor requests the default trending surface for the country. Output rows store `section: null`.

#### Which section values are allowed?

Exactly the select enum: `Now`, `Music`, `Gaming`, `Movies`.

#### Why did my run exit with code 1?

A hard error occurred during the trending fetch (HTTP failure after retries, invalid response, and so on). Check the Dataset `type: "error"` row and Actor logs.

#### Is this the cheapest ScrapeMamba YouTube Actor?

Yes on Apify pricing for this suite: **$1.70 / 1k** results.

#### Can I scrape trending for multiple countries in one run?

Not inside a single start. Launch one run per country (or automate a matrix). There is no country worker pool.

#### How fresh is the data?

As fresh as YouTube’s public trending surface at request time. What is **trending on YouTube** can change within minutes; treat every Dataset as a snapshot.

#### Do I need the official YouTube Data API?

No. ScrapeMamba `/youtube/trending` on Apify is enough — a practical **youtube scraper api** path for charts without Data API quotas.

#### Can I get full descriptions and like counts from trending alone?

Often not. Chain **YouTube Video Scraper** on the `videoId` list.

#### Is private or personalized trending supported?

No. Public data only.

#### How do I automate daily charts?

Use an Apify Schedule, sync the Dataset, and store the run timestamp for diffs.

#### Is this a YouTube video downloader?

No — trending **metadata** only, not media files.

***

### Pipeline patterns

**Pulse → enrich:** Trending → Video Scraper → optional Channel Scraper.\
**Pulse → graph:** Trending → Related Videos (dedupe before expensive steps).\
**Pulse → text:** Trending shortlist → Subtitles on priority IDs only.\
**Keyword vs chart:** Search for queries; Trending for platform-promoted charts.

***

### Export and automation

Dataset UI (JSON/CSV/Excel), Apify API/clients, Schedules, and webhooks for **YouTube trending videos** snapshots.

***

### Related ScrapeMamba Actors

| Actor | Best for |
|-------|----------|
| [YouTube Search Scraper](https://apify.com/scrapemamba/youtube-search-scraper) | Keyword discovery instead of charts |
| [YouTube Video Scraper](https://apify.com/scrapemamba/youtube-video-scraper) | Enrich trending IDs with fuller metadata |
| [YouTube Channel Scraper](https://apify.com/scrapemamba/youtube-channel-scraper) | Uploader profiles for chart creators |

Also: Channel Videos, Channel Shorts, Related Videos, Subtitles after you lock today’s ID list.

***

### Compliance note

Use only on **public** YouTube trending data, per YouTube’s terms, applicable law, and your policies. Do not access private content or circumvent controls.

# Actor input Schema

## `country` (type: `string`):

ISO country code (e.g. US, GB, IN).

## `lang` (type: `string`):

Optional UI language (e.g. en).

## `section` (type: `string`):

Optional trending shelf: Now, Music, Gaming, or Movies.

## `maxResults` (type: `string`):

Maximum videos to keep from the first trending page (1–500).

## Actor input object example

```json
{
  "country": "US",
  "lang": "en",
  "maxResults": "50"
}
```

# Actor output Schema

## `results` (type: `string`):

Default dataset items produced by this Actor.

# 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 = {
    "country": "US",
    "lang": "en",
    "maxResults": "50"
};

// Run the Actor and wait for it to finish
const run = await client.actor("scrapemamba/youtube-trending-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 = {
    "country": "US",
    "lang": "en",
    "maxResults": "50",
}

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

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

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

```

## CLI example

```bash
echo '{
  "country": "US",
  "lang": "en",
  "maxResults": "50"
}' |
apify call scrapemamba/youtube-trending-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,scrapemamba/youtube-trending-scraper"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

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