DEV Community

coreclaw
coreclaw

Posted on

Instagram Hashtag Tracker: How to Monitor Campaign Performance with Python

Best for: social media managers, growth marketers, and developers who need to report on Instagram hashtag campaigns without exporting spreadsheets by hand every week.

You can track an Instagram hashtag campaign programmatically by repeatedly collecting the public posts that use your tracked hashtags, normalizing those records into a consistent dataset, and computing reach-proxy metrics (post volume, engagement, top creators) on a fixed schedule. Below is a complete Python workflow that does exactly that, plus the operational limits you should know before you promise a client a dashboard.

TL;DR

  • Instagram's official Graph API supports hashtag search only for apps that pass review, and its scope is narrow — it is rarely practical for ongoing agency-style campaign monitoring.
  • The practical alternative is a scheduled pipeline: collect public posts for your tracked hashtags, deduplicate them, store each run as a dated snapshot, and compute trends between snapshots.
  • The Python example in this article is runnable once you supply your own endpoint URL and API key as environment variables.
  • Expect post counts and engagement numbers to be estimates of activity, not audited reach figures — Instagram does not expose impression-level data for posts you do not own.
  • Everything here works on publicly visible hashtag content only. Do not collect private accounts, private metrics, or anything behind a login.

Why hashtag tracking is harder than it looks

Most teams start with manual tracking: search the hashtag in the app, screenshot the top posts, paste counts into a slide. That breaks down quickly:

  1. No history. The hashtag page shows what is popular now. Once a post scrolls out of the "Top" grid, reconstructing last Tuesday's activity means scrolling through years of mixed content.
  2. No consistent metric. A "successful hashtag" for a sneaker drop (high volume, broad reach) looks nothing like a successful hashtag for a B2B SaaS launch (low volume, high comment quality). Manual tracking pushes everything toward the same vanity metric.
  3. Multiple hashtags, multiple campaigns. Agencies routinely run 10–40 hashtags across several clients. Manual collection does not scale past three.
  4. The official API path is constrained. Instagram's Graph API does include hashtag endpoints, but they require an approved app and business context, and the documentation is explicit that results are limited in scope. For many marketing teams that review process alone is a dealbreaker.

The realistic middle path: treat public hashtag content as a data source, collect it on a schedule through a managed extraction service, and do the analytics in Python where you control the metrics.

The workflow

The pipeline has five stages. Each stage is independent, so you can rerun any part without recollecting everything.

Stage Input Output Cadence
1. Collect List of hashtags Raw public post records (JSON) Every 6–24h during a campaign
2. Normalize Raw records Consistent schema: post_id, hashtag, owner, like_count, comment_count, timestamp, caption Every collection run
3. Deduplicate Normalized records Unique posts keyed by post_id Every collection run
4. Snapshot & diff Deduplicated dataset Per-run counts, new posts since last run, engagement deltas Every collection run
5. Report Snapshot series Weekly summary: volume trend, top posts, top creators, share of voice Weekly

Share of voice is the metric clients actually respond to: for a tracked hashtag set, what fraction of posts in the set mention your brand or campaign term (a simple case-insensitive caption match)? It turns "we got posts" into "we got 34% of the conversation this week."

Collecting the data

The collection step calls a managed scraper that returns structured public post data for a hashtag. This article uses CoreClaw's Instagram post scraper, which returns hashtag results as structured JSON rather than HTML, so stages 2–5 are pure data work.

The endpoint URL and API key are account-specific, so the code below reads them from environment variables. Copy the current endpoint from your console — do not copy a URL from an old blog post, including this one:

import os
import time
import requests

ENDPOINT = os.environ["CORECLAW_IG_ENDPOINT"]   # copy from your console
API_KEY = os.environ["CORECLAW_API_KEY"]

TRACKED_HASHTAGS = ["sneakerdrop", "streetweardaily", "kicks2026"]

def collect_hashtag(tag: str, max_records: int = 100) -> list[dict]:
    """Collect public posts for one hashtag. Returns a list of record dicts."""
    resp = requests.post(
        ENDPOINT,
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={"hashtag": tag, "max_records": max_records},
        timeout=60,
    )
    resp.raise_for_status()
    data = resp.json()
    records = data.get("records", data)  # tolerate slightly different shapes
    for r in records:
        r["hashtag"] = tag                # stamp provenance
        r["collected_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
    return records

def collect_all(tags: list[str]) -> list[dict]:
    all_records = []
    for tag in tags:
        all_records.extend(collect_hashtag(tag))
        time.sleep(2)                     # polite pacing between requests
    return all_records

if __name__ == "__main__":
    records = collect_all(TRACKED_HASHTAGS)
    print(f"Collected {len(records)} public post records")
Enter fullscreen mode Exit fullscreen mode

Two decisions worth defending:

  • time.sleep(2) between hashtags. A scheduled job that hammers an endpoint because a loop has no pacing is the most common self-inflicted failure in these pipelines. Two seconds costs nothing.
  • records = data.get("records", data). Extraction services evolve their response envelope. Writing the parser defensively at the boundary keeps one integration point instead of ten.

Normalizing and snapshotting

Raw records vary in field presence. Normalize before analyzing, then store each run as a dated JSONL snapshot so you can diff runs later:

import json
import pathlib
from datetime import datetime, timezone

SNAPSHOT_DIR = pathlib.Path("snapshots")

def normalize(records: list[dict]) -> list[dict]:
    clean = []
    for r in records:
        clean.append({
            "post_id": str(r.get("post_id") or r.get("id") or ""),
            "hashtag": (r.get("hashtag") or "").lower(),
            "owner": r.get("owner") or r.get("username") or "",
            "like_count": int(r.get("like_count") or 0),
            "comment_count": int(r.get("comment_count") or 0),
            "posted_at": r.get("posted_at") or r.get("timestamp") or "",
            "caption": (r.get("caption") or "")[:500],
            "collected_at": r.get("collected_at"),
        })
    # drop records with no usable id; deduplicate by post_id
    seen = set()
    unique = []
    for r in clean:
        if r["post_id"] and r["post_id"] not in seen:
            seen.add(r["post_id"])
            unique.append(r)
    return unique

def save_snapshot(records: list[dict]) -> pathlib.Path:
    SNAPSHOT_DIR.mkdir(exist_ok=True)
    path = SNAPSHOT_DIR / f"{datetime.now(timezone.utc):%Y-%m-%d}.jsonl"
    with path.open("a", encoding="utf-8") as f:
        for r in records:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")
    return path

def weekly_summary(records: list[dict], brand_terms: list[str]) -> dict:
    total = len(records)
    engagement = sum(r["like_count"] + r["comment_count"] for r in records)
    brand_posts = [r for r in records
                   if any(t.lower() in r["caption"].lower() for t in brand_terms)]
    top = sorted(records,
                 key=lambda r: r["like_count"] + r["comment_count"],
                 reverse=True)[:5]
    creators = {}
    for r in records:
        creators[r["owner"]] = creators.get(r["owner"], 0) + 1
    return {
        "total_posts": total,
        "total_engagement": engagement,
        "brand_posts": len(brand_posts),
        "share_of_voice": round(len(brand_posts) / total * 100, 1) if total else 0.0,
        "top_posts": [r["post_id"] for r in top],
        "most_active_creators": sorted(creators.items(), key=lambda kv: -kv[1])[:5],
    }
Enter fullscreen mode Exit fullscreen mode

Representative output (example values, not live data):

{
  "total_posts": 412,
  "total_engagement": 58740,
  "brand_posts": 141,
  "share_of_voice": 34.2,
  "top_posts": ["C_x91aBQ2rM", "C_x77kLpQ4nT"],
  "most_active_creators": [["sneaker.mika", 23], ["kicksdaily.hq", 17]]
}
Enter fullscreen mode Exit fullscreen mode

A note on interpretation: total_engagement sums public like and comment counts. It is a proxy for campaign energy, not reach. Two campaigns with identical engagement sums can differ wildly in actual impressions; say so in every report, because the first client who discovers you conflated the two will not forget it.

Scheduling it

Run collection every 6–24 hours while a campaign is live (more frequently only during launch windows, since hashtag grids churn fast). A minimal cron entry works:

# every 8 hours during the campaign
0 */8 * * * cd /opt/hashtag-tracker && ./venv/bin/python collect.py >> run.log 2>&1
Enter fullscreen mode Exit fullscreen mode

For team visibility, push the weekly summary into a shared sheet or Slack message rather than a local JSON file — a metric nobody sees is a metric that does not exist.

Common failure modes

Four failures account for most broken hashtag trackers. All four are cheap to prevent and expensive to discover three weeks into a campaign:

  1. Silent empty responses. The collector runs, returns zero records, and nobody notices because the script exits with status 0. Fix: alert whenever a scheduled run collects fewer records than a floor you set from the first week of data — a hashtag that reliably yields 200 posts per run does not drop to 4 posts without something breaking.
  2. Snapshot overwrites. A developer "fixes" the snapshot path and switches append to write mode, erasing history. The snapshot diff in stage 4 is the whole point of the pipeline; make snapshot files write-once and version the directory if multiple people touch the job.
  3. Post-ID drift. If the provider changes the ID field name between response versions, deduplication silently stops working and every run looks like brand-new posts. The normalize() function above coerces both common field names; additionally log the schema keys of the first record in each run so drift is visible in the log.
  4. Clock-skewed timestamps. Comparing collected_at values written by machines in different time zones produces negative deltas. Everything in this pipeline writes UTC explicitly — keep it that way, including in cron environments where local time is the default.

None of these require exotic engineering. They require deciding, up front, that a campaign-tracking pipeline is a small production system with an on-call answer — even when the on-call answer is just an alert to your own inbox.

How the collection options compare

Option Setup effort Data shape Historical snapshots Ongoing maintenance
Manual in-app tracking None Screenshots No High, per campaign
Official Graph API hashtag endpoints App review + business verification Structured, limited scope Build yourself Low once approved
Self-hosted scraper High You define it Build yourself High — selector and layout drift
Managed scraper API Low Structured JSON from the provider Build snapshots yourself (as above) Low — provider absorbs layout changes

The managed-scraper row is where CoreClaw's ready-made worker marketplace fits: hashtag collection is one prebuilt worker among many, so the pipeline above reduces to configuration plus the Python analytics layer. If the analytics layer itself is what you want to productize — packaging this exact workflow as a reusable tool — the CoreClaw Workers console is the deployment path.

Business use cases

  • Campaign reporting. Weekly share-of-voice and volume trend per hashtag set, per client. This is the core deliverable the pipeline exists for.
  • Influencer vetting. most_active_creators over a 2–4 week window is a shortlist of accounts genuinely producing content in the niche — a better outreach list than follower counts.
  • Hashtag selection. Compare candidate hashtags before committing a campaign to them: sustained volume with reasonable engagement per post beats spiky volume with comment spam.
  • Competitive monitoring. Track competitor-branded hashtags the same way you track your own; the pipeline does not care whose campaign it is measuring.

Limits and compliance

Be honest about these in proposals and reports:

  • Public data only. Everything above works on publicly visible posts. Private accounts, logged-in-only content, and private metrics (saves, reach, impressions) are out of scope — collecting them would violate Instagram's terms and, in many jurisdictions, privacy law.
  • Counts are estimates. Like and comment counts are public but shift; posts get deleted; engagement pods inflate numbers. Treat every figure as directional.
  • No personal-data retention beyond need. Captions and usernames are personal data under GDPR-style regimes. Store what the analysis needs, minimize fields, and define a retention period (30–90 days of snapshots is typical for campaign work).
  • Respect platform terms and provider policy. Follow Instagram's terms of service and your data provider's acceptable-use policy. Nothing here involves evading access controls, and it should stay that way.
  • Layout and schema drift. Providers absorb Instagram's front-end changes, but their response schema can evolve too. Version your parser and alert on unexpected field changes rather than failing silently.

FAQ

Does Instagram offer an official API for hashtag data?
Yes — the Graph API includes hashtag endpoints, but access requires an approved app and the scope is limited compared to what agencies typically need. Check Meta's current documentation before assuming it fits your use case.

What fields does the pipeline actually need per post?
Minimum: a stable post ID, owner handle, like count, comment count, post timestamp, and caption. Everything else is nice to have.

How often should collection run?
Every 6–24 hours during an active campaign is usually enough. Hourly runs add cost without adding signal for most hashtags.

What happens when Instagram changes its layout?
With a managed scraper, the provider fixes extraction and you may see schema changes in responses. With self-hosted scrapers, you fix it — usually within hours of a launch, which is why the maintenance row in the comparison table is marked high.

Can this feed a dashboard or an AI agent?
Yes. The snapshot JSONL files are plain structured data — loadable into any BI tool, and usable as grounded context for reporting agents. Keep the "these are public-data estimates" caveat attached to anything an agent summarizes.

What should I verify before running this in production?
Your provider's current endpoint format and quota terms, the response schema against a real test call, and your own retention policy for the personal data in captions and usernames.

Start tracking

Set up a workspace in the CoreClaw Workers console, grab the Instagram post scraper worker, and point the script above at it — the full collection-to-report pipeline is under 150 lines of Python. For a deeper walkthrough of extracting public Instagram content and the field-level details behind the pipeline above, the CoreClaw Instagram post scraper product page covers the scraper's output fields in detail.

If you are evaluating the broader build-vs-buy decision first, browse CoreClaw's ready-made worker marketplace and compare it against your current tracking stack before committing the analytics layer.

Top comments (0)