# YouTube Comments Scraper (Sentiment & Market Research) (`accommodating_aptitude/youtube-comments`) Actor

Pulls video comments via the official YouTube Data API v3: full text, author, channel link, like count, date and replies. Includes like-count and keyword filters. For sentiment analysis and market research. Bring your own free API key (BYOK).

- **URL**: https://apify.com/accommodating_aptitude/youtube-comments.md
- **Developed by:** [Korhan Coşan Ergün](https://apify.com/accommodating_aptitude) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$2.00 / 1,000 comment founds

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?

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 Comments Scraper (Sentiment & Market Research)

Pulls video comments, their authors and like counts via the official
**YouTube Data API v3** `commentThreads.list` endpoint. For sentiment analysis,
market research, product-feedback mining and brand monitoring.

### Bring your own API key (BYOK)

The `youtubeApiKey` input is **required** and is stored as a secret. To get one
for free:

1. [console.cloud.google.com](https://console.cloud.google.com) → new project
2. **APIs & Services → Library** → "YouTube Data API v3" → **Enable**
3. **APIs & Services → Credentials → Create credentials → API key**

`commentThreads.list` = **1 quota unit per 100 comments**. The free quota of
10,000 units per day ≈ **1,000,000 comments**.

### Input

```json
{
  "youtubeApiKey": "***",
  "videoUrls": ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"],
  "maxCommentsPerVideo": 100,
  "order": "relevance",
  "includeReplies": true,
  "minLikeCount": 0,
  "searchTerms": []
}
```

- `order`: `relevance` (top comments — recommended for sentiment analysis) or `time`
- `includeReplies`: replies become separate records too (`is_reply=true`, `parent_comment_id` filled in)
- `minLikeCount`: skip comments with fewer likes than this
- `searchTerms`: when supplied, only comments containing one of these words are
  written (case-insensitive) — useful for filtering brand/product feedback

### Output fields

| Field | Description |
|---|---|
| `comment_id`, `link` | Comment id and a direct deep link (`...&lc=<id>`) |
| `text`, `text_length`, `title` | Full comment text, its length, a shortened title |
| `author_display_name`, `author_channel_id`, `author_channel_url`, `author_profile_image_url` | Author |
| `like_count` | Like count |
| `published_at`, `updated_at`, `is_edited` | Timing information and whether it was edited |
| `is_reply`, `parent_comment_id`, `total_reply_count` | Thread structure |
| `video_id`, `video_title`, `video_url` | Which video it belongs to |
| `can_rate`, `viewer_rating` | API metadata fields |

Pagination is automatic: `nextPageToken` is followed until
`maxCommentsPerVideo` is reached or the comments run out. Videos with comments
disabled (`commentsDisabled`) are skipped and logged.

### Pricing

Pay-per-event: **`comment-found` → $0.002**. You are only charged per comment
actually written to the dataset (filtered-out comments are free).

### robots.txt note

`youtube.com/robots.txt` disallows the `/comment` path, but this actor does
**not** use the web page — it uses the official API on `googleapis.com`, where
that robots.txt restriction does not apply; the YouTube API Services ToS applies
instead.

### Local test

```bash
bash ../_common/vendor_common.sh .
APIFY_LOCAL=1 YOUTUBE_API_KEY=*** python3 main.py
```

Without a key (code-path verification only):

```bash
python3 test_fixtures.py
```

> `test_fixtures.py` starts a local HTTP server that imitates the API (including
> pagination). The response bodies are written to match the field structure in
> Google's official API reference: **structurally correct, but the data is
> synthetic.** `sample_output.json` is also derived from that fixture run (an
> example structure, not live data).

# Actor input Schema

## `youtubeApiKey` (type: `string`):

Your own free key. How to get it: console.cloud.google.com -> APIs & Services -> Library -> 'YouTube Data API v3' -> Enable -> Credentials -> Create credentials -> API key. A free quota of 10,000 units per day, 100 comments = 1 unit (so ~1,000,000 comments per day). Alternatively it can be set as the actor environment variable YOUTUBE_API_KEY; if left empty, the actor logs the key-acquisition instructions and finishes with an empty result.

## `videoUrls` (type: `array`):

The YouTube videos whose comments should be pulled. A full URL (watch, youtu.be, shorts, embed) or an 11-character video ID.

## `maxCommentsPerVideo` (type: `integer`):

Maximum number of comments to pull from each video (replies count towards it when included).

## `order` (type: `string`):

relevance = YouTube's 'top comments' ordering (recommended for sentiment analysis). time = newest to oldest.

## `includeReplies` (type: `boolean`):

When enabled, replies to top-level comments are also written as separate records (is_reply=true, parent_comment_id filled in).

## `minLikeCount` (type: `integer`):

Comments with fewer likes than this are skipped. 0 = no filter.

## `searchTerms` (type: `array`):

When supplied, only comments containing at least one of these words are written (case-insensitive). Useful for product/brand feedback mining.

## Actor input object example

```json
{
  "videoUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ],
  "maxCommentsPerVideo": 100,
  "order": "relevance",
  "includeReplies": true,
  "minLikeCount": 0
}
```

# Actor output Schema

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

Dataset containing all records found in this run.

# 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 = {
    "videoUrls": [
        "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("accommodating_aptitude/youtube-comments").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 = { "videoUrls": ["https://www.youtube.com/watch?v=dQw4w9WgXcQ"] }

# Run the Actor and wait for it to finish
run = client.actor("accommodating_aptitude/youtube-comments").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 '{
  "videoUrls": [
    "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
  ]
}' |
apify call accommodating_aptitude/youtube-comments --silent --output-dataset

```

## MCP server setup

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

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/mvjww8iIuitgiY7Cn/builds/BqHMtBVhubYT21M8t/openapi.json
