# Instagram Posts Search Scraper (`outspoken_strategy/instagram-post-search-scraper`) Actor

Search Instagram posts by keyword or hashtag (prefix with #). Multiple keywords, date-range filter, auto-pagination. Returns caption, author, likes, comments, views and media URLs. Requires a session (cookies or automated login) — Instagram login-walls all search.

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

## Pricing

from $8.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 Posts Search Scraper

Apify actor that searches Instagram posts by keyword or hashtag and exports them as
structured data.

**A session is required.** Instagram login-walls ALL search and hashtag pages (there
is no anonymous access at all), so the actor authenticates like our Twitter/Facebook
actors do — 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 from a previous automated login (persistent key-value store)
4. automated login with `igUsername`/`igPassword` (or `IG_USERNAME`/`IG_PASSWORD`
   env vars) — best-effort: Instagram aggressively challenges automated logins, so
   manually exported cookies are more reliable

**Always use a throwaway account**, keep the proxy country stable and matching the
account's usual region, and expect the account to need an occasional manual login to
clear checkpoints.

### How it works

A real Chrome (Playwright) opens Instagram's search page
(`/explore/search/keyword/?q=...`, or `/explore/tags/...` for `#hashtag` queries)
with the session. The page fires Instagram's own search GraphQL query
(`PolarisKeywordSearchExplorePageRelayQuery`); the actor then pages through the
results by replaying the pagination query (`...RelayPaginationQuery`) with the
`after` cursor, reusing the page's own request tokens. Post data is extracted by a
generic walker that understands Instagram's media shapes, so it survives layout
shuffles.

- **Keywords with no posts.** For some broad keywords (e.g. `zimbabwe`,
  `artificial intelligence`) Instagram returns only an accounts/hashtags block and
  no posts — the web app itself shows "No results". The actor then automatically
  falls back to the keyword's hashtag (`#zimbabwe`, `#artificialintelligence`);
  those items have `matchedVia: "hashtag"`.
- **Full details.** Search results only carry basic fields, so by default
  (`enrichDetails: true`) each returned post's full info is fetched
  (`/api/v1/media/{id}/info/`) to add views, location, tagged users, coauthors,
  music, Reel/product type, reshares and alt text (~1–2 s per post).
- Residential proxy exits are preflighted before the browser launches, and results
  are pushed after each keyword so an abort keeps partial data.

### Input

```json
{
    "queries": ["econet", "#zimbabwe"],
    "numberOfPosts": 100,
    "start_date": "2026-01-01",
    "end_date": "2026-06-30",
    "enrichDetails": true,
    "proxySessionId": "igacct1",
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": ["RESIDENTIAL"],
        "apifyProxyCountry": "US"
    }
}
```

- `numberOfPosts` applies **per keyword**.
- `start_date` / `end_date` (yyyy-mm-dd, inclusive, UTC) are enforced actor-side
  from each post's timestamp — Instagram search has no date operators and ranks by
  relevance, not date. Only posts inside the range count toward `numberOfPosts`,
  so pagination continues past out-of-range posts (up to 60 pages per keyword).
  A narrow or old range can therefore return fewer posts than requested.
  `timeSince` / `timeUntil` are still accepted as aliases.
- `scrapeAll: false` returns only the first results page.
- `debug: true` saves every API/GraphQL response, a screenshot, the HTML and raw
  media samples to the run's key-value store.

### Output

One dataset item per post:

```json
{
    "id": "3672339888759474360",
    "code": "DK9xY2LMnPq",
    "url": "https://www.instagram.com/reel/DK9xY2LMnPq/",
    "text": "Full caption of the post... #harare @econet",
    "hashtags": ["harare"],
    "mentions": ["econet"],
    "username": "some_user",
    "fullName": "Some User",
    "userId": "1234567890",
    "profileUrl": "https://www.instagram.com/some_user/",
    "profilePicUrl": "https://scontent.cdninstagram.com/...",
    "isVerified": false,
    "isPrivateAccount": false,
    "likes": 42,
    "likesHidden": false,
    "comments": 7,
    "commentsDisabled": false,
    "views": 1250,
    "reshares": 3,
    "mediaType": "video",
    "isVideo": true,
    "productType": "clips",
    "isReel": true,
    "displayUrl": "https://scontent.cdninstagram.com/...",
    "images": ["https://scontent.cdninstagram.com/..."],
    "videoUrl": "https://scontent.cdninstagram.com/...",
    "videoDuration": 16.37,
    "hasAudio": true,
    "width": 720,
    "height": 1280,
    "alt": null,
    "carouselCount": null,
    "childPosts": [],
    "location": { "id": "213385402", "name": "Harare, Zimbabwe", "shortName": null, "address": null, "city": null, "lat": -17.8, "lng": 31.0 },
    "taggedUsers": [{ "username": "friend", "fullName": "Friend", "userId": "5", "isVerified": false, "profilePicUrl": "..." }],
    "coauthors": [],
    "music": { "title": "Original audio", "artist": "some_user", "audioId": "123", "isOriginalAudio": true },
    "isPaidPartnership": false,
    "sponsors": [],
    "created_at": "2026-07-01T09:30:12.000Z",
    "createdUtc": 1782898212,
    "searchQuery": "econet",
    "matchedVia": "keyword"
}
```

`mediaType` is `image`, `video` or `carousel`; carousels list every slide in
`childPosts` (type, image/video URL, size) and `images`. `productType: "clips"`
marks Reels. Missing values are `null` / empty arrays.

### Integration (scraping-tool)

Call it like the other `outspoken_strategy/*` search actors:

```js
const res = await this.scrapingService.scrape({
    url: `https://www.instagram.com/explore/search/keyword/?q=${encodeURIComponent(keyword)}`,
    resultsLimit: requestCount,
    actor: 'outspoken_strategy/instagram-post-search-scraper',
    timeout,
    additionalInput: {
        query: keyword,
        numberOfPosts: requestCount,
        headless: true,
        proxyConfiguration: { useApifyProxy: true, apifyProxyGroups: ['RESIDENTIAL'], apifyProxyCountry: 'US' }
    },
    scrapeType: 'instagram-keyword-search'
});
```

Set `IG_COOKIES` (or `IG_USERNAME`/`IG_PASSWORD`) as secret env vars on the actor —
same pattern as `TW_COOKIES`/`FB_COOKIES` — and optionally `IG_PROXY_SESSION` to pin
the account to one exit IP. Normalization hints: `url` and `id` are
ready to use; `text` is the caption; `likesCount` ← `likes`, `commentsCount` ←
`comments`, `viewsCount` ← `views`, `createdTime` ← `created_at`; author fields are
`username`/`fullName`/`userId`/`profileUrl`.

### Local development

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

Deploy with `apify push`.

# Actor input Schema

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

One keyword/phrase to search for, e.g. "econet". Prefix with # to search a hashtag page instead (e.g. "#zimbabwe"). You can also paste several keywords, one per line, to search them all. For a clean list use the "queries" field below instead. Leave empty if you use "queries".

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

Multiple keywords/hashtags to search — each is searched separately and results are combined and de-duplicated by post. Takes precedence over/adds to "query". numberOfPosts applies PER keyword.

## `numberOfPosts` (type: `integer`):

Maximum number of posts to fetch per keyword.

## `scrapeAll` (type: `boolean`):

Keep scrolling until numberOfPosts is reached or the feed runs dry. When unchecked only the first page of results is returned.

## `enrichDetails` (type: `boolean`):

Search results only include basic fields. When enabled, each returned post's full details are fetched too: views/plays, location, tagged users, coauthors, music, Reel/product type, reshares, alt text. Adds roughly 1–2 seconds per post.

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

Only return posts published on or after this date (format: yyyy-mm-dd, UTC).

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

Only return posts published on or before this date, inclusive (format: yyyy-mm-dd, UTC).

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

Cookies of a logged-in Instagram session, exported with a browser extension such as Cookie-Editor or EditThisCookie (JSON array of {name, value, domain, ...}). REQUIRED in practice: the "sessionid" cookie carries the session. Alternatively set the IG_COOKIES secret environment variable on the actor (same JSON, or a 'name=value; name2=value2' string) to avoid passing cookies in every run. Use a throwaway account, never your personal one.

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

Username of a throwaway Instagram account. If set together with igPassword (or via the IG_USERNAME/IG_PASSWORD secret env vars), the actor logs in itself and caches the session, so you don't need to paste cookies. The account must have 2FA disabled. Note: Instagram aggressively challenges automated logins — cookies from a manually authenticated session are more reliable.

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

Password for the account in igUsername. Stored encrypted. Prefer the IG_PASSWORD secret environment variable instead of putting it in run input.

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

Set a stable id here (or via the IG_PROXY_SESSION env var) to keep the account on ONE exit IP across runs. Instagram flags sessions that hop IPs/regions. Use one distinct id per Instagram account, e.g. "igacct1". Leave empty to use a fresh random IP each run.

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

Proxy to route traffic through. Residential proxies with a country set are strongly recommended — Instagram blocks datacenter IPs and flags sessions that hop regions, so keep the proxy country stable and matching the account's usual region.

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

Uncheck to run a headed browser (useful only for local debugging).

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

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

## Actor input object example

```json
{
  "query": "artificial intelligence",
  "queries": [],
  "numberOfPosts": 100,
  "scrapeAll": true,
  "enrichDetails": true,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "apifyProxyCountry": "US"
  },
  "headless": true,
  "debug": false
}
```

# Actor output Schema

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

Posts with the key fields (URL, caption, author, engagement, type, location, hashtags, publish date, keyword).

## `results` (type: `string`):

Full post records including media URLs, carousel items, tagged users, coauthors, music and sponsor info.

# 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": "artificial intelligence",
    "queries": [],
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ],
        "apifyProxyCountry": "US"
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("outspoken_strategy/instagram-post-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": "artificial intelligence",
    "queries": [],
    "proxyConfiguration": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
        "apifyProxyCountry": "US",
    },
}

# Run the Actor and wait for it to finish
run = client.actor("outspoken_strategy/instagram-post-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": "artificial intelligence",
  "queries": [],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "apifyProxyCountry": "US"
  }
}' |
apify call outspoken_strategy/instagram-post-search-scraper --silent --output-dataset

```

## MCP server setup

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