# Youtube Scraper (`ayuugoyal/youtube-scraper`) Actor

A powerful Apify Actor that scrapes YouTube videos from channels, playlists, or search results without using the official YouTube API. Built with Python and the scrapetube library.

- **URL**: https://apify.com/ayuugoyal/youtube-scraper.md
- **Developed by:** [Ayush Goyal](https://apify.com/ayuugoyal) (community)
- **Categories:** Social media, Lead generation, Videos
- **Stats:** 14 total users, 0 monthly users, 7.1% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

## 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 Scraper Actor

A powerful Apify Actor that scrapes YouTube videos from channels, playlists, or search results without using the official YouTube API. Built with Python and the scrapetube library.

### Features

- **Channel Scraping**: Get videos from any YouTube channel
  - Support for channel ID, URL, or username
  - Filter by content type (videos, shorts, streams)
  - Sort by newest, oldest, or popular

- **Playlist Scraping**: Extract all videos from any playlist

- **Search Scraping**: Search YouTube and get results
  - Filter by result type (video, channel, playlist, movie)
  - Sort by relevance, upload date, view count, or rating

- **No API Key Required**: Uses scrapetube to scrape data without YouTube API limitations

- **Proxy Support**: Optional proxy configuration to avoid blocking

- **Structured Output**: Clean, normalized data with thumbnails, view counts, and more

### Input Parameters

#### Required

- **scrapeType** (string): Choose what to scrape - `channel`, `playlist`, or `search`

#### Channel Scraping

- **channelId** (string): YouTube channel ID (e.g., `UCXuqSBlHAE6Xw-yeJA0Tunw`)
- **channelUrl** (string): Full channel URL (alternative to channel ID)
- **channelUsername** (string): Channel username without @ (alternative to channel ID)
- **contentType** (string): Type of content - `videos`, `shorts`, or `streams` (default: `videos`)
- **sortBy** (string): `newest`, `oldest`, or `popular` (default: `newest`)

#### Playlist Scraping

- **playlistId** (string): YouTube playlist ID

#### Search Scraping

- **searchQuery** (string): Search term to find videos
- **resultsType** (string): `video`, `channel`, `playlist`, or `movie` (default: `video`)
- **sortBy** (string): `relevance`, `upload_date`, `view_count`, or `rating` (default: `relevance`)

#### Common Parameters

- **maxVideos** (integer): Maximum number of videos to scrape (default: 100)
- **sleepInterval** (number): Seconds to sleep between requests to prevent blocking (default: 1)
- **proxyUrls** (array): Optional proxy URLs in format `http://username:password@host:port`

### Output

The actor outputs structured data for each video including:

- **videoId**: YouTube video ID
- **title**: Video title
- **url**: Full YouTube URL
- **channelName**: Channel name
- **channelId**: Channel ID
- **viewCount**: Number of views
- **publishedTime**: When the video was published
- **lengthText**: Video duration
- **thumbnailUrl**: Video thumbnail image URL
- **descriptionSnippet**: Short description excerpt
- **rawData**: Complete raw data from scrapetube

### Example Usage

#### Scrape Latest Videos from a Channel

```json
{
  "scrapeType": "channel",
  "channelUsername": "LinusTechTips",
  "contentType": "videos",
  "sortBy": "newest",
  "maxVideos": 50
}
```

#### Search YouTube

```json
{
  "scrapeType": "search",
  "searchQuery": "python tutorial",
  "resultsType": "video",
  "sortBy": "view_count",
  "maxVideos": 100
}
```

#### Scrape a Playlist

```json
{
  "scrapeType": "playlist",
  "playlistId": "PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf",
  "maxVideos": 200
}
```

### Local Development

#### Prerequisites

- Python 3.11+
- Apify CLI

#### Install Apify CLI

**Windows:**

```powershell
irm https://apify.com/install-cli.ps1 | iex
```

**macOS/Linux:**

```bash
curl -fsSL https://apify.com/install-cli.sh | bash
```

#### Setup and Run

1. Install dependencies:

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

2. Create a local input file `.actor/INPUT.json`:

```json
{
  "scrapeType": "search",
  "searchQuery": "apify tutorial",
  "maxVideos": 10
}
```

3. Run locally:

```bash
apify run
```

#### Deploy to Apify Platform

1. Login to Apify:

```bash
apify login
```

2. Push the actor:

```bash
apify push
```

### Technical Details

- **Runtime**: Python 3.11
- **Base Image**: apify/actor-python:3.11
- **Main Libraries**:
  - `apify` - Apify SDK for Python
  - `scrapetube` - YouTube scraping library

### Notes

- The actor respects YouTube's structure and implements rate limiting via `sleepInterval`
- No authentication or API key required
- Data extraction is based on YouTube's public HTML structure
- Some fields may be unavailable depending on the video/channel

### Contributing

This actor was generated as part of the Apify AI Challenge. Feel free to submit improvements!

### License

ISC

### Support

For issues or questions, please open an issue on the GitHub repository.

# Actor input Schema

## `scrapeType` (type: `string`):

Choose what you want to scrape from YouTube.

## `channelId` (type: `string`):

The channel ID (e.g., UCXuqSBlHAE6Xw-yeJA0Tunw). Only used when scrapeType is 'channel'.

## `channelUrl` (type: `string`):

The full URL to the channel. Alternative to Channel ID. Only used when scrapeType is 'channel'.

## `channelUsername` (type: `string`):

The channel username (e.g., LinusTechTips without the @). Alternative to Channel ID. Only used when scrapeType is 'channel'.

## `playlistId` (type: `string`):

The playlist ID to scrape videos from. Only used when scrapeType is 'playlist'.

## `searchQuery` (type: `string`):

The search term to find videos. Only used when scrapeType is 'search'.

## `maxVideos` (type: `integer`):

Maximum number of videos to scrape. Leave empty for unlimited.

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

How to sort the results. For channels: newest/oldest/popular. For search: relevance/upload_date/view_count/rating.

## `contentType` (type: `string`):

Type of content to scrape from channels. Only used when scrapeType is 'channel'.

## `resultsType` (type: `string`):

Type of results to return from search. Only used when scrapeType is 'search'.

## `sleepInterval` (type: `number`):

Seconds to sleep between API calls to prevent blocking.

## `proxyUrls` (type: `array`):

Optional proxy URLs to use for requests (format: http://username:password@host:port).

## Actor input object example

```json
{
  "scrapeType": "search",
  "maxVideos": 100,
  "sortBy": "newest",
  "contentType": "videos",
  "resultsType": "video",
  "sleepInterval": 1,
  "proxyUrls": []
}
```

# Actor output Schema

## `videos` (type: `string`):

All scraped YouTube videos

## `overview` (type: `string`):

Quick overview of scraped videos

# 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 = {
    "channelId": "",
    "channelUrl": "",
    "channelUsername": "",
    "playlistId": "",
    "searchQuery": "",
    "maxVideos": 100,
    "sleepInterval": 1,
    "proxyUrls": []
};

// Run the Actor and wait for it to finish
const run = await client.actor("ayuugoyal/youtube-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 = {
    "channelId": "",
    "channelUrl": "",
    "channelUsername": "",
    "playlistId": "",
    "searchQuery": "",
    "maxVideos": 100,
    "sleepInterval": 1,
    "proxyUrls": [],
}

# Run the Actor and wait for it to finish
run = client.actor("ayuugoyal/youtube-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 '{
  "channelId": "",
  "channelUrl": "",
  "channelUsername": "",
  "playlistId": "",
  "searchQuery": "",
  "maxVideos": 100,
  "sleepInterval": 1,
  "proxyUrls": []
}' |
apify call ayuugoyal/youtube-scraper --silent --output-dataset

```

## MCP server setup

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