# YouTube Search Results Scraper (`w3crawler/youtube-search-scraper`) Actor

Collect current YouTube search results for videos, Shorts, channels, and playlists with paginated, deduplicated metadata and locale-aware source context.

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

## Pricing

from $2.99 / 1,000 search results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## YouTube Public Search Scraper

Collect deduplicated public YouTube search results for videos, Shorts, channels, and playlists. The actor requests the ordinary rendered search page and parses its embedded public `ytInitialData`; it does not call the private YouTube search API or rotate client fingerprints.

### Dataset

Every result includes the submitted query, stable rank, page number, actual result type, title, public URL, source location, locale, enrichment provenance, and scrape time. When YouTube exposes the fields, the record also includes video/playlist/channel IDs, channel links, verification badges, displayed counts plus parsed counts, duration, live/upcoming flags, descriptions, accessibility text, thumbnails, playlist previews, search filters, and the exact public renderer source.

Blocked pages, unavailable embedded metadata, and empty matches are represented by exactly four diagnostic fields: `url`, `error`, `errorCode`, and `scrapedAt`. Per-run counts and proxy state are written to the `OUTPUT` key-value record.

### Input

| Field | Default | Description |
| --- | --- | --- |
| `query` | required | Public YouTube keyword or phrase, up to 500 characters. |
| `maxItems` | `50` | Maximum unique results, 1–500. |
| `maxPages` | `3` | Bounded public page requests, 1–30. The actor uses the normal `page` query parameter and stops when a page is empty or duplicate. |
| `resultType` | `all` | `all`, `video`, `short`, `channel`, or `playlist`. |
| `sortBy` | `relevance` | `relevance`, `upload_date`, `view_count`, or `rating`; type-specific searches use relevance. |
| `languageCode` / `countryCode` | `en` / `US` | Locale context passed to the public search page. |
| `proxyConfiguration` | none | Optional account-authorized Apify Proxy or credential-free HTTP/SOCKS URLs. |
| `enableProxyFallback` | `true` | Try one ordinary Apify Proxy request after a direct public-page failure. |
| `includeDiagnostics` | `true` | Keep bounded diagnostics in the dataset. |
| `requestDelayMs` / `requestTimeoutSecs` | `250` / `60` | Pacing and bounded request timeout. |

### Example

```json
{
  "query": "machine learning",
  "maxItems": 25,
  "resultType": "video",
  "sortBy": "relevance",
  "maxPages": 2,
  "countryCode": "US",
  "enableProxyFallback": true,
  "includeDiagnostics": true,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

### Reliability and limits

- Uses a fixed ordinary browser User-Agent and public HTML only.
- Proxy requests are account-authorized and are summarized as booleans in `OUTPUT`; proxy URLs, credentials, cookies, and request identities are never written to result rows.
- Does not implement fingerprint spoofing, stealth patches, CAPTCHA/login bypass, private or alternate YouTube clients, or hidden API calls.
- Search results, ranking, locale, badges, counts, and availability are point-in-time public observations.
- `maxPages` is a safety limit, not a guarantee that YouTube will expose that many public pages.

### Local verification

```powershell
npm test
npx --yes apify validate-schema
$env:APIFY_LOCAL_STORAGE_DIR = 'storage'
npx --yes apify run --purge --input-file INPUT.json
node validate-datasets.js
```

The checked-in `storage/` sample contains the latest local run. Before replacing it, preserve the existing store as a backup.

# Changelog

This Actor's version history is a separate document: https://apify.com/w3crawler/youtube-search-scraper/changelog.md

# Actor input Schema

## `query` (type: `string`):

Keyword or phrase to search on YouTube.

## `maxItems` (type: `integer`):

Maximum number of unique public results to save.

## `maxPages` (type: `integer`):

Bounded number of rendered public search pages to request. Pagination uses the ordinary page query parameter and stops on duplicate pages.

## `resultType` (type: `string`):

Keep all public result types or request videos, Shorts, channels, or playlists.

## `sortBy` (type: `string`):

Public YouTube search filter. Type-specific searches must use relevance.

## `languageCode` (type: `string`):

YouTube UI language code, such as en or pt-BR.

## `countryCode` (type: `string`):

Two-letter country code used by the public search page for locale context.

## `proxyConfiguration` (type: `object`):

Optional account-authorized Apify Proxy or credential-free HTTP/SOCKS proxy URLs. Proxy state is summarized only in OUTPUT.

## `enableProxyFallback` (type: `boolean`):

After a direct public-page failure, try one ordinary Apify Proxy request. No fingerprint spoofing or private client is used.

## `includeDiagnostics` (type: `boolean`):

Write bounded four-field diagnostics for blocked pages, unavailable result metadata, and failed requests.

## `requestDelayMs` (type: `integer`):

Pacing delay between public page requests.

## `requestTimeoutSecs` (type: `integer`):

Bounded timeout for each public search page request.

## Actor input object example

```json
{
  "query": "machine learning",
  "maxItems": 50,
  "maxPages": 3,
  "resultType": "all",
  "sortBy": "relevance",
  "languageCode": "en",
  "countryCode": "US",
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "enableProxyFallback": true,
  "includeDiagnostics": true,
  "requestDelayMs": 250,
  "requestTimeoutSecs": 60
}
```

# Actor output Schema

## `dataset` (type: `string`):

No description

## `keyValueStore` (type: `string`):

No description

# 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 = {
    "query": "machine learning",
    "maxItems": 50,
    "maxPages": 3,
    "resultType": "all",
    "sortBy": "relevance",
    "languageCode": "en",
    "countryCode": "US",
    "proxyConfiguration": {
        "useApifyProxy": false
    },
    "enableProxyFallback": true,
    "includeDiagnostics": true,
    "requestDelayMs": 250,
    "requestTimeoutSecs": 60
};

// Run the Actor and wait for it to finish
const run = await client.actor("w3crawler/youtube-search-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 = {
    "query": "machine learning",
    "maxItems": 50,
    "maxPages": 3,
    "resultType": "all",
    "sortBy": "relevance",
    "languageCode": "en",
    "countryCode": "US",
    "proxyConfiguration": { "useApifyProxy": False },
    "enableProxyFallback": True,
    "includeDiagnostics": True,
    "requestDelayMs": 250,
    "requestTimeoutSecs": 60,
}

# Run the Actor and wait for it to finish
run = client.actor("w3crawler/youtube-search-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 '{
  "query": "machine learning",
  "maxItems": 50,
  "maxPages": 3,
  "resultType": "all",
  "sortBy": "relevance",
  "languageCode": "en",
  "countryCode": "US",
  "proxyConfiguration": {
    "useApifyProxy": false
  },
  "enableProxyFallback": true,
  "includeDiagnostics": true,
  "requestDelayMs": 250,
  "requestTimeoutSecs": 60
}' |
apify call w3crawler/youtube-search-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,w3crawler/youtube-search-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/5oCosAIjwtXBT0vcO/builds/haTgDkOaPpDAOGEbZ/openapi.json
