# Instagram Comments Scraper (`outspoken_strategy/instagram-comments-scraper`) Actor

Scrape comments and replies from any Instagram post or reel. Paste post/reel URLs; get comment text, author, likes, reply count, timestamps and threading. Date-range filter, popular/newest ordering. Requires a session (cookies or automated login).

- **URL**: https://apify.com/outspoken_strategy/instagram-comments-scraper.md
- **Developed by:** [code craker](https://apify.com/outspoken_strategy) (community)
- **Features:** Limited permissions
- **Stats:** 8 total users, 4 monthly users, 60.5% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $5.00 / 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?

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

## Instagram Comments Scraper

Apify actor that scrapes comments — and optionally replies — from any Instagram post,
reel or IGTV video and exports them as structured data.

**A session is required.** Instagram only serves comments to logged-in sessions. The
actor authenticates the same way as the Instagram post search actor, in priority order:

1. `cookies` input — a JSON cookie export from a logged-in browser (Cookie-Editor /
   EditThisCookie); the `sessionid` cookie carries the session
2. `IG_COOKIES` secret env var on the actor (same JSON, or a `name=value; ...` string)
3. the cached session in the `instagram-session` key-value store (needs full permissions)
4. automated login with `igUsername`/`igPassword` (or `IG_USERNAME`/`IG_PASSWORD`)

**Always use a throwaway account.** Optionally set `IG_PROXY_SESSION` (e.g. `igacct1`) so
the account keeps one exit IP across runs.

### How it works

A real Chrome (Playwright) opens the first post once with the session — HTML document
only, Instagram's scripts, styles and media are not downloaded — and verifies the
session via `/api/v1/media/{id}/info/` (owner, caption, comment count). Every post is
then read through Instagram's comments API (`/api/v1/media/{id}/comments/`,
`next_min_id` cursor) called from inside that logged-in page, with no further page
loads. Reply threads come from `/api/v1/media/{id}/comments/{commentId}/child_comments/`
and are fetched right after their parent comment. If the comments API is unavailable
for a post that has at least 25 comments, the actor falls back to loading the full page
and collecting the comments it loads while scrolling.

#### Cost controls

The run stops collecting once the user's maximum charge for the run is reached, so no
comments are scraped that cannot be charged for. It also tracks its own estimated
platform cost (proxy traffic and compute) against what it has earned and stops early
when the cost outgrows the earnings — for example a date-filtered scan of a long thread
that matches almost nothing, or a long list of posts without comments. The thresholds
are the constants at the top of `src/main.js`.

Shortcodes are decoded to media ids locally, so post, reel, IGTV, profile-scoped and
share (`?igsh=`) links all work, as do bare shortcodes.

### Input

```json
{
    "startUrls": [{ "url": "https://www.instagram.com/p/De9ZzxeAJ76/" }],
    "postUrls": ["https://www.instagram.com/reel/DfXn6bByKOn/", "DexT0nAy7ok"],
    "maxComments": 200,
    "includeReplies": true,
    "maxRepliesPerComment": 20,
    "start_date": "2026-11-01",
    "end_date": "2026-11-30",
    "proxyConfiguration": { "useApifyProxy": true, "apifyProxyGroups": ["RESIDENTIAL"], "apifyProxyCountry": "US" }
}
```

- `maxComments` is **per post**; replies count toward it when `includeReplies` is on.
- `start_date` / `end_date` (yyyy-mm-dd, inclusive, UTC) filter on each comment's time.
  Instagram's web API only returns comments in its relevance order (there is no
  newest-first option), so with a date filter the actor scans the thread and keeps
  only matching comments.
- Aliases for compatibility: `directUrls` (= `postUrls`), `resultsLimit`
  (= `maxComments`), `includeNestedComments` (= `includeReplies`).
- `debug: true` saves Instagram's responses, a screenshot and the HTML to the run's
  key-value store.

### Output

One dataset item per comment:

```json
{
    "id": "18013753928992349",
    "commentId": "18013753928992349",
    "text": "This is amazing!! Would you ever consider ...",
    "mentions": [],
    "hashtags": [],
    "date": "2026-10-26T18:44:09.000Z",
    "timestamp": 1793040249,
    "likesCount": 17,
    "repliesCount": 1,
    "isReply": false,
    "parentCommentId": null,
    "threadingDepth": 0,
    "commentUrl": "https://www.instagram.com/p/De9ZzxeAJ76/c/18013753928992349/",
    "isPinned": false,
    "isLikedByPostOwner": false,
    "isEdited": false,
    "isHidden": false,
    "isRankedComment": true,
    "contentType": "comment",
    "hasTranslation": false,
    "author": {
        "id": "123456", "username": "selah_studio_za", "fullName": "Selah Studio",
        "profileUrl": "https://www.instagram.com/selah_studio_za/",
        "profilePicUrl": "https://scontent.cdninstagram.com/...",
        "isVerified": false, "isPrivate": false
    },
    "ownerId": "123456",
    "ownerUsername": "selah_studio_za",
    "ownerFullName": "Selah Studio",
    "ownerProfileUrl": "https://www.instagram.com/selah_studio_za/",
    "ownerProfilePicUrl": "https://scontent.cdninstagram.com/...",
    "ownerIsVerified": false,
    "postUrl": "https://www.instagram.com/p/De9ZzxeAJ76/",
    "postId": "4016479951657148154",
    "postShortcode": "De9ZzxeAJ76",
    "postOwnerUsername": "mosseri",
    "postCaption": "Sat down with @tessalyonsss ...",
    "postCommentsCount": 2025,
    "postCreatedAt": "2026-10-26T15:00:40.000Z",
    "inputUrl": "https://www.instagram.com/p/De9ZzxeAJ76/",
    "scrapedAt": "2026-11-06T09:33:46.826Z"
}
```

Replies have `isReply: true`, `threadingDepth: 1` and `parentCommentId` set.
`isHidden` marks comments Instagram covers as potentially offensive. GIF/sticker
comments have an empty `text`. `postCommentsCount` is Instagram's count (it includes
replies, and can exceed what is retrievable when comments are deleted or restricted).

### Local development

```bash
npm install
mkdir -p storage/key_value_stores/default
cat > storage/key_value_stores/default/INPUT.json <<'JSON'
{ "postUrls": ["DexT0nAy7ok"], "maxComments": 30,
  "cookies": [ ...exported from a logged-in browser... ],
  "proxyConfiguration": { "useApifyProxy": false } }
JSON
npm start
```

Deploy with `apify push`.

# Actor input Schema

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

Instagram post, reel or IGTV URLs to scrape comments from, e.g. https://www.instagram.com/p/DexT0nAy7ok/ or https://www.instagram.com/reel/DexT0nAy7ok/. Profile-scoped links and share links with ?igsh=… work too.

## `postUrls` (type: `array`):

Alternative to startUrls: a plain list of post/reel URLs or bare shortcodes (e.g. "DexT0nAy7ok"). Merged with startUrls and de-duplicated.

## `maxComments` (type: `integer`):

Maximum number of comments to collect for EACH post (replies count toward this limit when included).

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

Also collect replies to comments. Replies have isReply=true and parentCommentId set. Slower on posts with long threads.

## `maxRepliesPerComment` (type: `integer`):

Optional cap on replies collected per comment thread (only used when Include replies is on). Leave empty for no cap.

## `start_date` (type: `string`):

Only return comments posted on or after this date (format: yyyy-mm-dd).

## `end_date` (type: `string`):

Only return comments posted on or before this date, inclusive (format: yyyy-mm-dd).

## `cookies` (type: `array`):

Cookies of a logged-in Instagram session exported with Cookie-Editor / EditThisCookie (JSON array). The "sessionid" cookie carries the session. Alternatively set the IG_COOKIES env var.

## `igUsername` (type: `string`):

Throwaway account username (2FA off). Used only when no valid cookies are available; the session is then cached and reused. Prefer the IG_USERNAME env var.

## `igPassword` (type: `string`):

Password for igUsername. Prefer the IG_PASSWORD secret env var.

## `resultsLimit` (type: `integer`):

Alias kept for integrations built against other Instagram comment actors. Ignored when maxComments is set.

## `directUrls` (type: `array`):

Alias of postUrls for compatibility.

## `includeNestedComments` (type: `boolean`):

Alias of includeReplies.

## `proxySessionId` (type: `string`):

Stable id (or the IG_PROXY_SESSION env var) to keep the account on ONE exit IP across runs — Instagram flags sessions that hop IPs. One id per account, e.g. "igacct1".

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

Residential proxies with a fixed country are strongly recommended; Instagram blocks datacenter IPs.

## `headless` (type: `boolean`):

Uncheck only for local debugging.

## `debug` (type: `boolean`):

Save Instagram API/GraphQL responses, a screenshot and the page HTML to the run's key-value store. For troubleshooting.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://www.instagram.com/p/De9ZzxeAJ76/"
    }
  ],
  "maxComments": 50,
  "includeReplies": false,
  "includeNestedComments": false,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "apifyProxyCountry": "US"
  },
  "headless": true,
  "debug": false
}
```

# Actor output Schema

## `comments` (type: `string`):

All scraped comments, one item per comment (replies included when enabled).

## `commentsOverview` (type: `string`):

The overview view of the dataset: post, author, text, likes, replies, date.

## `debugFiles` (type: `string`):

Key-value store of the run; holds DEBUG\_\* screenshots, HTML and API responses when debug mode is on.

# 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 = {
    "startUrls": [
        {
            "url": "https://www.instagram.com/p/De9ZzxeAJ76/"
        }
    ],
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ],
        "apifyProxyCountry": "US"
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("outspoken_strategy/instagram-comments-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 = {
    "startUrls": [{ "url": "https://www.instagram.com/p/De9ZzxeAJ76/" }],
    "proxyConfiguration": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
        "apifyProxyCountry": "US",
    },
}

# Run the Actor and wait for it to finish
run = client.actor("outspoken_strategy/instagram-comments-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 '{
  "startUrls": [
    {
      "url": "https://www.instagram.com/p/De9ZzxeAJ76/"
    }
  ],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "apifyProxyCountry": "US"
  }
}' |
apify call outspoken_strategy/instagram-comments-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,outspoken_strategy/instagram-comments-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/qpOwagwgJ6BwsZ5rP/builds/dhzopfRWd2euHJYaH/openapi.json
