# YouTube Comment Sentiment Scraper (`googleapi/youtube-comment-sentiment-scraper`) Actor

Analyze public YouTube comments with bounded sentiment, topic and spam heuristics using ordinary public browsing or an opt-in official YouTube Data API route.

- **URL**: https://apify.com/googleapi/youtube-comment-sentiment-scraper.md
- **Developed by:** [Google API](https://apify.com/googleapi) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.99 / 1,000 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

### What this Actor does

YouTube Comment Sentiment Scraper collects public comments available for YouTube videos and labels each comment using a deterministic English keyword lexicon. It can also report matched topics and simple text-based spam signals.

Sentiment is a transparent heuristic, not an AI assessment, moderation decision, or probability. A neutral label means no configured positive or negative terms matched; it does not prove the commenter felt neutral.

### Input

Provide public video URLs or video IDs. You can also use search terms or public YouTube search URLs to discover videos. `maxVideos` limits videos inspected, `maxCommentsPerVideo` limits comments per video, and `maxItems` caps dataset rows across the run.

```json
{"videoUrls":["https://www.youtube.com/watch?v=jNQXAC9IVRw"],"maxCommentsPerVideo":50,"maxItems":50}
```

```json
{"queries":["beginner science tutorial"],"maxVideos":5,"maxCommentsPerVideo":25,"sortComments":"top"}
```

`includeReplies` is off by default and includes replies only when they are already visible in the public page. `includeVideoMetadata` adds public video title, description, channel, date, duration, and view information.

An optional official YouTube Data API route is available and is **off by default**. To use it, enable `useYouTubeDataApi` and configure `youtubeApiKey` as a secret in Apify. Do not put an API key in the input JSON. API results depend on the key's permissions and available quota. Enabling `useYouTubeDataApi` without a key stops the run explicitly: it emits zero rows, makes zero API requests, and never falls back to the restricted public browse route. The same API-only isolation applies to any API failure — a failure is recorded in the key-value store with an explicit status (`API_EXECUTION_FAILED` / `COMMENTS_DISABLED`) and is never rewritten as success. Comments disabled at the source produce zero business rows plus a structured KVS status.

You can provide IDs with `videoIds`, use `query` or `searchQuery` for one search, or use `searchUrls` for public YouTube `/results` pages. `deduplicate` is enabled by default, and `locale` sets the language preference for generated searches and public pages.

### Dataset output

Each row contains a `videoId`, `commentId`, comment `text`, and a `sentiment` object. Other available fields include the video title and URL, channel identity, comment author display name, like/reply counts, reply relationship, publication text, topics, and spam indicators.

```json
{
  "videoId": "jNQXAC9IVRw",
  "videoUrl": "https://www.youtube.com/watch?v=jNQXAC9IVRw",
  "commentId": "UgxExamplePositive",
  "text": "This clear tutorial is great and very helpful!",
  "authorName": "Example Viewer",
  "likeCount": 12,
  "replyCount": 2,
  "isReply": false,
  "sentiment": {
    "label": "positive",
    "score": 1,
    "method": "fixed_english_keyword_lexicon",
    "positiveMatches": ["clear", "great", "helpful"],
    "negativeMatches": []
  },
  "topics": ["education"],
  "spamSignals": {"isLikelySpam": false, "reasons": []}
}
```

The sentiment score is bounded between -1 and 1 and is based on the matched words. Each `sentiment` object records its `version`, `model`, `rulesVersion`, and `rulesHash`. The score is a deterministic English-lexicon keyword balance, **not** calibrated statistical confidence (`confidenceIsCalibrated: false`, `scoreIsStatisticalConfidence: false`); a `neutral` label means no configured term matched, not that the commenter felt neutral. The classifier is local and entirely distinct from the comment source. Only the comments actually retrieved were classified; the exact sampled count, limitations, and the **publication HOLD** are reported in the key-value store (`sentimentGovernance`). No population-wide audience claim, complete-audience-sentiment claim, or sensitive-attribute profiling is made — two sampled comments are never a complete audience-sentiment analysis. Live API-derived sentiment publication remains on HOLD until the applicable viewer-sentiment analytics amendment is accepted by the developer; this project does not claim that acceptance. `spamSignals` are indicators only, not a moderation verdict. The Actor does not infer unavailable comments or fill failed sources with placeholder rows.

Download dataset results in JSON, CSV, Excel, or another format supported by Apify. The run page also displays a summary and source status.

### Cost, coverage, and responsible use

Check the Actor's Pricing tab for current Actor and Apify platform charges. More videos and higher comment limits increase collection volume. The official Data API route uses the configured key's quota.

Only comments exposed on public video pages or through the configured official API are collected. Comments may contain personal information shared by their authors. Follow YouTube's terms and applicable privacy laws, and use the results only for a legitimate purpose.

# Actor input Schema

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

HTTPS YouTube watch, Shorts, live, embed, youtu.be URLs, or 11-character video IDs. This is the primary source input.

## `startUrls` (type: `array`):

Compatibility alias for videoUrls. Each item must be an object with a YouTube video URL.

## `sourceUrls` (type: `array`):

Compatibility alias for videoUrls.

## `urls` (type: `array`):

Legacy compatibility alias for videoUrls.

## `videoIds` (type: `array`):

11-character YouTube video IDs.

## `queries` (type: `array`):

Public YouTube search terms used to discover video cards before comments are requested.

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

One compatibility search query; equivalent to a one-item queries array.

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

Legacy alias for query.

## `searchUrls` (type: `array`):

HTTPS /results URLs containing search_query. Query parameters are preserved while observed next links are followed.

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

Global maximum number of normal comment records emitted across all videos and sources.

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

Per-video collection cap before the global maxItems limit is applied.

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

Maximum explicit or search-discovered videos to inspect.

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

Maximum observed search pages per query or search URL. The Actor never calls undocumented continuation endpoints.

## `startPage` (type: `integer`):

Compatibility alias for page. YouTube search exposes cursor-based Next links, not a stable numeric page offset; only the initial page (1) is supported.

## `deduplicate` (type: `boolean`):

Remove duplicate video sources and comment IDs across pages and queries.

## `sortComments` (type: `string`):

Keep YouTube source order (top) or order comments by the relative age text when YouTube exposes it (new). No unavailable date is invented.

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

Compatibility alias for sortComments; allowed values are top and new.

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

Include replies only when they are already rendered in the public page or present in embedded data; no continuation API is called.

## `includeVideoMetadata` (type: `boolean`):

Include public title, description, channel, publication, duration, view, live, and thumbnail fields from the watch page.

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

Delay between ordinary source requests; 0 is allowed for local fixtures.

## `maxConcurrency` (type: `integer`):

Bounded browser-page concurrency. The default is sequential to preserve source order and limit public traffic.

## `maxRequestRetries` (type: `integer`):

Bounded retries for transient public HTTP failures.

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

Timeout for each public HTML request.

## `maxResponseBytes` (type: `integer`):

Bound for HTML/fixture text retained for parsing.

## `userAgent` (type: `string`):

Optional ordinary user-agent string for direct HTTP discovery; it is not rotated or used for access-control evasion. Browser rendering uses its normal browser user agent.

## `locale` (type: `string`):

BCP-47-like locale sent in Accept-Language and used for generated search URLs.

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

Optional Apify Proxy configuration wired into direct HTTP discovery and ordinary browser requests. It does not bypass CAPTCHA or access controls; proxy credentials are never logged.

## `page` (type: `integer`):

Starting page for video search discovery. YouTube exposes cursor-based Next links rather than a stable numeric offset, so only page 1 is supported.

## `useYouTubeDataApi` (type: `boolean`):

Select the official API for public comments and optional video metadata, including documented search discovery. Requires the secret youtubeApiKey. Disabled by default.

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

Configure an already authorized YouTube Data API v3 key securely in Apify. Never include it in source files or example input. Ignored unless useYouTubeDataApi is enabled. API requests go directly to Google; proxyConfiguration applies to browser requests.

## Actor input object example

```json
{
  "maxItems": 100,
  "maxCommentsPerVideo": 100,
  "maxVideos": 25,
  "maxPages": 1,
  "startPage": 1,
  "deduplicate": true,
  "sortComments": "top",
  "includeReplies": false,
  "includeVideoMetadata": true,
  "requestDelayMs": 250,
  "maxConcurrency": 1,
  "maxRequestRetries": 1,
  "requestTimeoutSecs": 30,
  "maxResponseBytes": 2000000,
  "locale": "en-US",
  "page": 1,
  "useYouTubeDataApi": false
}
```

# Actor output Schema

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

No description

## `summary` (type: `string`):

No description

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

// Run the Actor and wait for it to finish
const run = await client.actor("googleapi/youtube-comment-sentiment-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("googleapi/youtube-comment-sentiment-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 '{}' |
apify call googleapi/youtube-comment-sentiment-scraper --silent --output-dataset

```

## MCP server setup

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