Export Instagram Comments to CSV or Excel with Python

Export Instagram comments to CSV or Excel with Python: 1 credit returns the 15 newest comments. Poll to capture a whole giveaway, then draw winners.

By Scrape Everything team · · 11 min read

Last updated: December 3, 2026

TL;DR: To export Instagram comments to CSV, send the post or Reel URL to POST /v1/instagram/comments, flatten the comments array with pandas.json_normalize, and call to_csv or to_excel. Each call costs 1 credit and returns up to the 15 newest top-level comments plus the post's total comment_count.

Fifteen is the most this endpoint returns for a post. A small giveaway fits in one call. A bigger one needs polling during the entry window, and this guide covers that, plus a winner draw anyone can re-run from your published CSV.

An Instagram comment export is a flat table with one row per public comment (ID, text, time, likes and the commenter's username) that you can sort, filter and dedupe in Excel, Google Sheets or pandas.

Which way should you export Instagram comments?

There are three realistic routes, and they suit different people. If you don't write code and only need your own post once, a browser extension is probably the faster path. This guide is for the scripted case.

MethodInstagram loginWhat you getRepliesCost to tryFits
Browser extensionYes, it runs inside your logged-in sessionWhatever the page loads as you scrollDepends on the extensionVaries by extensionOne-off exports of your own posts, no code
Instagram Graph API (Meta's Instagram Platform)Your business or creator account, a Meta app and an access tokenComments on media you ownYesNo per-call fee, but app setupYour own posts at any size
Scrape Everything instagram.commentsNone15 newest top-level comments per call, plus the total comment_countNo100 free credits, 1 credit per callPosts you don't own, scripted CSV or Excel, polled giveaways

The trade-off with extensions is that your own Instagram account makes the requests, so read the extension's terms and warnings before you point it at a big post. The Instagram Graph API is the right tool for your own business account at scale. For everything else, the rest of this post uses the Instagram scraper API, which reads public data only and needs no Meta app. Scrape Everything isn't affiliated with Instagram or Meta.

How do I export Instagram comments to CSV?

  1. Sign in at /login with Google or GitHub. You get 100 free credits and nobody asks for payment details. Put your ssk_live_... key in an environment variable named SCRAPEEVERYTHING_API_KEY.
  2. Copy the post or Reel URL from the share menu. /p/, /reel/ and /tv/ links all work, and so does the bare shortcode.
  3. Call the Instagram comments scraper with that URL.
  4. Flatten data.comments into a DataFrame and write it out.

Step 3 as a cURL request:

bash
curl -X POST https://api.scrapeeverything.com/v1/instagram/comments \
  -H "Authorization: Bearer $SCRAPEEVERYTHING_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://www.instagram.com/p/DYxz0A8Kinw/", "limit": 15}'

The response, trimmed to two comments. Values are placeholders; field names match the endpoint schema.

json
{
  "success": true,
  "data": {
    "shortcode": "DYxz0A8Kinw",
    "link": "https://www.instagram.com/p/DYxz0A8Kinw/",
    "comment_count": 214,
    "comments": [
      {
        "id": "18012345678901234",
        "text": "@example_friend we need this one",
        "created_at": 1796292000,
        "like_count": 3,
        "reply_count": null,
        "gif_url": null,
        "author": {
          "id": "1234567890",
          "username": "example_user",
          "profile_pic_url": "https://scontent.cdninstagram.com/...jpg",
          "is_verified": false
        }
      },
      {
        "id": "18012345678904321",
        "text": "",
        "created_at": 1796291820,
        "like_count": 0,
        "reply_count": null,
        "gif_url": "https://media.giphy.com/...gif",
        "author": {
          "id": "9876543210",
          "username": "another_user",
          "profile_pic_url": "https://scontent.cdninstagram.com/...jpg",
          "is_verified": false
        }
      }
    ],
    "comments_fetched": 15,
    "has_more": true
  },
  "meta": {
    "request_id": "req_...",
    "scraper": "instagram.comments",
    "cached": false,
    "credits_charged": 1,
    "credits_remaining": 99
  }
}

Read comment_count: 214 next to has_more: true as "this post has 214 comments and you're holding 15 of them."

What fields come back for each comment?

Every field below is in the endpoint schema in the API reference. After json_normalize, the nested author object becomes author_* columns.

Column after flatteningTypeNotes
idstringComment ID. Your dedupe key when merging polls.
textstringEmpty for GIF-only and other media-only comments.
created_atinteger, nullableUnix seconds. Convert before writing Excel.
like_countinteger, nullableLikes on the comment.
reply_countinteger, nullableNull in every comment we sampled; don't rely on it.
gif_urlstring, nullableSet for GIF comments.
author_idstring, nullableNumeric user ID as a string.
author_usernamestring, nullableThe handle you announce winners by.
author_profile_pic_urlstring, nullableSigned CDN link. The signature expires, so don't treat it as a permanent image URL.
author_is_verifiedbooleanVerified badge.

Two things aren't there. Commenters' display names (full_name) aren't returned, and replies aren't returned, only top-level comments. If your giveaway rules say "reply to this comment to enter", rewrite the rules.

How do I export Instagram comments to Excel with pandas?

The script below handles one post. Install requests, pandas and openpyxl; pandas picks the .xlsx writer (openpyxl or XlsxWriter) from what's installed, as the pandas to_excel docs describe.

bash
pip install requests pandas openpyxl
python
# export_comments.py
import os
import sys

import pandas as pd
import requests

BASE = "https://api.scrapeeverything.com"
HEADERS = {"Authorization": f"Bearer {os.environ['SCRAPEEVERYTHING_API_KEY']}"}


def call(path: str, payload: dict) -> dict:
    r = requests.post(BASE + path, json=payload, headers=HEADERS, timeout=60)
    try:
        body = r.json()
    except ValueError:
        raise RuntimeError(f"{r.status_code}: response was not JSON") from None
    if not body.get("success"):
        raise RuntimeError(f"{r.status_code} {body.get('code')}: {body.get('message')}")
    return body["data"]


def fetch_comments(url: str) -> dict:
    return call("/v1/instagram/comments", {"url": url, "limit": 15})


def defuse(value):
    # OWASP CSV injection list: cells starting with these can run as formulas.
    if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
        return "'" + value
    return value


def to_frame(data: dict) -> pd.DataFrame:
    df = pd.json_normalize(data["comments"], sep="_")
    if df.empty:
        return df
    df.insert(0, "post_shortcode", data["shortcode"])
    # Excel can't store timezone-aware datetimes: keep UTC, drop the tz label.
    df["created_at"] = (
        pd.to_datetime(df["created_at"], unit="s", utc=True).dt.tz_localize(None)
    )
    df["text"] = df["text"].map(defuse)
    return df


if __name__ == "__main__":
    data = fetch_comments(sys.argv[1])
    df = to_frame(data)
    print(f"{len(df)} of {data['comment_count']} comments (has_more={data['has_more']})")
    df.to_csv("comments.csv", index=False, encoding="utf-8-sig")
    df.to_excel("comments.xlsx", index=False, sheet_name="comments")

Run it with python export_comments.py https://www.instagram.com/p/DYxz0A8Kinw/.

Each of these lines fixes a bug you'd otherwise hit:

  • encoding="utf-8-sig" writes a byte order mark. Without it, Excel on Windows often opens the CSV in a legacy code page and every emoji turns into mojibake.
  • tz_localize(None) exists because to_excel raises a ValueError on timezone-aware datetimes. The values are still UTC, so label the column that way if someone else reads the sheet.
  • defuse prefixes risky leading characters with an apostrophe, following the OWASP CSV injection guidance. Comment text is user input. This matters for the .xlsx too, not only the CSV: openpyxl writes any string starting with = as a formula.

The @ entry is a trade-off. Giveaway comments often start with a tag, so plenty of rows in text will show a leading apostrophe. We'd rather have that than a cell Excel tries to interpret. The draw below reads usernames, not text, so the prefix never touches who wins.

A 404 with PRIVATE_ACCOUNT or AGE_RESTRICTED means the post exists but isn't publicly viewable. That's a final answer and it's billed, so don't retry it in a loop. The errors page lists which codes are refunded.

To get the file into Google Sheets, use File > Import and upload comments.csv, or open comments.xlsx from Drive. If you'd rather have a sheet that refills itself on a schedule, our guide to tracking Instagram followers in Google Sheets shows the Apps Script pattern.

How do I capture every giveaway entry when only 15 comments are visible?

The endpoint returns at most the 15 newest top-level comments of a post. Older ones aren't available, so raising limit won't change it.

Giveaway entries arrive during a window you set, which makes timing the fix. Call the endpoint on a schedule while the window is open and keep every comment ID you haven't seen. If fewer than 15 new comments land between two polls, you have all of them.

This loop appends each new comment to a JSONL file, so a crash or a sleeping laptop doesn't lose what you've collected. It reuses fetch_comments from the script above.

python
# poll_comments.py
import json
import time
from pathlib import Path

import requests

from export_comments import fetch_comments

POST_URL = "https://www.instagram.com/p/DYxz0A8Kinw/"
CLOSES_AT = 1796551200          # entry deadline, Unix seconds (UTC)
EVERY = 300                     # seconds between polls
store = Path("comments.jsonl")

seen = set()
if store.exists():
    with store.open(encoding="utf-8") as f:
        seen = {json.loads(line)["id"] for line in f}

last_count = None
last_ok = time.time()
while time.time() < CLOSES_AT + EVERY:  # one extra poll after the deadline
    try:
        data = fetch_comments(POST_URL)
    except (RuntimeError, requests.RequestException) as exc:
        print(f"poll failed: {exc} (last success {int(time.time() - last_ok)}s ago)")
        time.sleep(EVERY)
        continue
    last_ok = time.time()
    new = [c for c in data["comments"] if c["id"] not in seen]
    with store.open("a", encoding="utf-8") as f:
        for c in new:
            f.write(json.dumps(c, ensure_ascii=False) + "\n")
            seen.add(c["id"])
    count = data["comment_count"]
    if last_count is not None and new and len(new) == data["comments_fetched"]:
        print(f"possible gap: all {len(new)} comments were new, poll more often")
    if last_count is not None and count is not None and count - last_count > len(new):
        print(f"comment_count rose by {count - last_count}, captured {len(new)}")
    last_count = count
    time.sleep(EVERY)

Three warnings are built in. If every comment in a response is new, you probably missed some, so shorten EVERY. If comment_count jumps by more than you captured, same story, though deletions make that check approximate. And if polls keep failing, the "last success" counter tells you how much of the window you've lost.

Leave cache_days out of polling requests. Caching returns a stored result for free, which is great for a re-read and wrong for catching new entries.

At 5-minute polls the ceiling is roughly 15 new comments per 5 minutes. A post that collects thousands of comments in its first hour will outrun that at any polling interval you'd want to pay for. For a post on your own business or creator account, use the Instagram Graph API from the table above. Polling suits small and mid-size giveaways and posts you don't own.

How do I export comments for many posts at once?

Start from the profile. instagram.photos returns up to 60 recent posts with their links for 2 credits. Its per-post comment_count came back null in every post we sampled, so the zero-comment skip below only saves credits when a count is present.

python
import pandas as pd

from export_comments import call, fetch_comments, to_frame

posts = call("/v1/instagram/photos", {"username": "example_user", "limit": 30})["posts"]

frames, skipped = [], []
for p in posts:
    if p.get("comment_count") == 0:  # null means "unknown", so fetch those
        continue
    try:
        frames.append(to_frame(fetch_comments(p["link"])))
    except RuntimeError as exc:
        skipped.append((p["shortcode"], str(exc)))

if frames:
    pd.concat(frames, ignore_index=True).to_excel("all_comments.xlsx", index=False)
for shortcode, reason in skipped:
    print("skipped", shortcode, reason)

One failed post no longer throws away the frames you've already paid for. comment_count in the posts list is usually null, which is why the skip tests for 0 and lets null through. For Reels, call /v1/instagram/reels and read data["reels"]; the Instagram Reels scraper API guide covers that response.

The loop runs sequentially on purpose. The free plan allows 60 requests per minute and 5 concurrent, which is plenty for one profile.

How do I pick a fair Instagram giveaway winner?

Fair means one entry per person and a draw someone else can reproduce from your published data.

  1. Before entries open, post the rules and a seed string in the caption. A pattern like <brand>-<campaign>-<number> works, for example acme-giveaway-03. Publishing it in advance means you can't go looking for a seed that favors a friend.
  2. After the deadline, build the entrant list: drop the account that posted, drop comments after the deadline, apply any rule filters, then keep each commenter's earliest remaining comment.
  3. Sort entrants by username so the order doesn't depend on how the API or your polling returned them.
  4. Draw with random.Random(seed).sample(...) and publish entrants.csv next to the winners.
python
import json
import random

import pandas as pd

from export_comments import defuse

SEED = "acme-giveaway-03"
OWNER = "example_brand"
CLOSES_AT = pd.Timestamp(1796551200, unit="s")
MIN_TAGS = 2  # rule: "tag 2 friends". Set to 0 if you don't require tags.

with open("comments.jsonl", encoding="utf-8") as f:
    rows = [json.loads(line) for line in f]
df = pd.json_normalize(rows, sep="_")
df["created_at"] = pd.to_datetime(df["created_at"], unit="s")
df["entrant"] = df["author_username"].fillna(df["author_id"])
df["tags"] = df["text"].str.count(r"@[A-Za-z0-9._]+")

entrants = (
    df[(df["created_at"] <= CLOSES_AT) & (df["entrant"] != OWNER)]
    .loc[lambda d: d["tags"] >= MIN_TAGS]          # rule filter BEFORE the dedupe
    .sort_values("created_at")
    .drop_duplicates("entrant", keep="first")
    .sort_values("entrant")
)
out = entrants[["entrant", "id", "created_at", "tags", "text"]].copy()
out["text"] = out["text"].map(defuse)
out.to_csv("entrants.csv", index=False, encoding="utf-8-sig")

winners = random.Random(SEED).sample(list(entrants["entrant"]), k=3)
print(winners)

The tag rule sits before drop_duplicates on purpose. If you filter afterwards, someone whose first comment had one tag and whose second had two gets thrown out instead of counted. Rows with a null created_at fall out at the deadline filter, so check how many that removes.

Use random.Random(seed) rather than a picker website: anyone with Python and your entrants.csv gets the same three names. String seeds have used the same seeding scheme since Python 3.2, but the random module docs only promise that random() itself stays reproducible across versions, so put your Python version in the announcement. random is fine for a public draw; the docs warn against it for anything security-sensitive.

Some rules this data can't check. "Must follow us" needs a follower list, which this endpoint doesn't return, so verify winners by hand before you announce. One person entering from several accounts isn't detectable from public comment data either.

Giveaways also come with platform rules and local promotion law, and we can't tell you what applies to yours. Our post on whether scraping public social media data is legal lists the questions worth asking. Usernames are personal data, so delete comments.jsonl once the prizes ship.

How many credits does an Instagram comment export cost?

Costs per endpoint are listed on /pricing. Cache hits cost 0, and blocks, timeouts and 5xx errors are refunded automatically; a definitive 404 such as PRIVATE_ACCOUNT is charged.

JobEndpointCredits
Up to 15 newest comments on one post or Reelinstagram.comments1
Up to 60 recent posts with links and captionsinstagram.photos2
Up to 50 reels from the Reels tabinstagram.reels2
30 posts from one profile, all with commentsphotos + 30 x comments32
Poll one post every 5 minutes for 72 hoursinstagram.comments x 864864
Poll one post every 10 minutes for 7 daysinstagram.comments x 1,0081,008

What the 100 free credits cover: a one-off export of a single post, a 30-post profile export, or about 8 hours of polling at 5-minute intervals (about 16 hours at 10 minutes). That's enough for a same-evening flash giveaway and not enough for a 3-day one.

For longer windows, credits come in one-time packs that never expire. The Builder pack is $19.99 for 25,000 credits ($0.80 per 1,000), which covers 28 72-hour giveaways at 5-minute polls. At that rate, a 72-hour giveaway costs about $0.69 of credit and a 7-day one at 10-minute polls about $0.81. The credit calculator does the same math for your own interval.

Put together: a 3-day giveaway polled every 5 minutes uses 864 credits, and after the dedupe you publish one entrants.csv with one row per commenter and a 3-winner draw from a seed you announced on day one.

If you'd rather not keep a Python loop alive for three days, the n8n node can call the same endpoint from a schedule trigger. The endpoint is also in the OpenAPI spec at https://scrapeeverything.com/openapi.json, and once the entries are in a DataFrame, our guide to scoring comments for sentiment shows what else you can do with them.

Get 100 free credits

FAQ

Can I export all comments on an Instagram post, not just the newest 15?

Not in one call. The endpoint returns at most the 15 newest top-level comments, so that's what you get, with the total in comment_count. For a giveaway, poll during the entry window as shown above; for your own business account, the Instagram Graph API pages through all comments.

Can I check that giveaway entrants follow the account?

Not with the comments endpoint. It returns each commenter's username, ID, profile picture and verified flag, but no follower relationship. Check the winners by hand before announcing them.

How do I open the export in Google Sheets?

Upload comments.csv with File > Import, or open comments.xlsx from Google Drive. Write the CSV with encoding="utf-8-sig" so emoji survive if someone opens the same file in Excel later.

Does this work for Instagram Reels?

Yes. Send a /reel/ URL or the shortcode to /v1/instagram/comments. It's the same endpoint and the same 1 credit as a photo post.

Why is the text column empty for some comments?

Those are GIF-only or other media-only comments, and the GIF link is in gif_url. Decide in your rules whether a GIF counts as an entry, then filter on text or gif_url.

Why does Excel show broken emoji in my CSV?

Excel guessed the wrong encoding. Write the file with encoding="utf-8-sig" as in the script, or skip CSV and use to_excel, which stores text as Unicode.

More from the blog

Start with 100 free credits.

Continue with Google, create an API key and send your first request in under a minute.

Get 100 free credits