Tutorial · Instagram · Python

Scrape Instagram comments to CSV with Python

To scrape comments from an Instagram post with Python, page through /v1/instagram/posts/{post}/comments with requests, then fetch replies only for comments whose reply_count is above zero. The script below writes comments and replies to one CSV, with a parent_id column to keep threads together.

Short answer. Run python instagram_comments.py C9xYzAbCdEf newest (a post link works too) with HANDLEHAUL_API_KEY set. You get comments_C9xYzAbCdEf.csv: id, time, author, likes, reply count and text. About 15 comments per call, so 1,000 comments take about 67 calls, $0.094 to $0.054, plus reply pages.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

What you need

  • An API key. Sign up and create one in the dashboard. A sandbox key (kd_test_) returns sample data for free, so you can run the script before you spend anything.
  • Python 3.9 or newer and the requests package (pip install requests). csv, os and the rest come with Python.
  • The key in HANDLEHAUL_API_KEY. The script reads it from the environment, so the key never sits in your code or your repository.
  • Public Instagram posts. The API returns public data only: no logins, no private accounts, no DMs.

The script

It calls GET /v1/instagram/posts/{post}/comments and GET /v1/instagram/comments/{comment}/replies (see the Instagram comments API docs), retries on 429 using Retry-After, and stops with a clear message on any other error. Save it as instagram_comments.py.

instagram_comments.py
# Export every comment on a public Instagram post (and the replies) to CSV.
# Usage: python instagram_comments.py <shortcode or post URL> [top|newest] [max_pages]
# Needs Python 3.9+, the requests package and HANDLEHAUL_API_KEY in the environment.
import csv
import re
import os
import sys
import time
from urllib.parse import quote

import requests

API = "https://api.handlehaul.com"
KEY = os.environ.get("HANDLEHAUL_API_KEY")
if not KEY:
    sys.exit("Set HANDLEHAUL_API_KEY first, e.g. export HANDLEHAUL_API_KEY=kd_live_...")

session = requests.Session()
session.headers["X-Api-Key"] = KEY


class ApiError(Exception):
    def __init__(self, status, code, message):
        super().__init__(f"HTTP {status} {code}: {message}")
        self.status = status
        self.code = code


def get(path, params=None):
    # One API call. Waits and retries on 429 (honouring Retry-After) and on 502/503/504,
    # raises ApiError for any other error. Failed calls and 429 answers are not charged.
    for attempt in range(6):
        r = session.get(API + path, params=params, timeout=60)
        if r.status_code in (429, 502, 503, 504) and attempt < 5:
            try:
                wait = float(r.headers.get("Retry-After", ""))
            except ValueError:
                wait = 2 ** attempt
            print(f"  HTTP {r.status_code}, retrying in {wait:g}s", file=sys.stderr)
            time.sleep(wait)
            continue
        try:
            body = r.json()
        except ValueError:
            body = {}
        if r.ok:
            return body
        err = body.get("error") or {}
        raise ApiError(r.status_code, err.get("code", "unknown"), err.get("message", r.text[:200]))


FIELDS = ["id", "parent_id", "created_at", "username", "full_name", "like_count", "reply_count", "text"]
MAX_REPLY_PAGES = 5  # per comment; set 0 to skip replies


def walk(path, params, max_pages):
    # Yields one page at a time, following pagination.next_cursor.
    params = dict(params)
    for _ in range(max_pages):
        body = get(path, params)
        yield body
        if not body["pagination"]["has_more"]:
            return
        params["cursor"] = body["pagination"]["next_cursor"]


def row(c, parent_id=""):
    return {"id": c["id"], "parent_id": parent_id, "created_at": c["created_at"],
            "username": c["author"]["username"], "full_name": c["author"]["full_name"],
            "like_count": c["like_count"], "reply_count": c.get("reply_count", 0), "text": c["text"]}


def main():
    if len(sys.argv) < 2:
        sys.exit("Usage: python instagram_comments.py <shortcode or post URL> [top|newest] [max_pages]")
    post = sys.argv[1]
    m = re.search(r"/(?:p|reels?|tv)/([\w-]+)", post)
    if m:
        post = m.group(1)  # https://www.instagram.com/p/C9xYzAbCdEf/ -> C9xYzAbCdEf
    sort = sys.argv[2] if len(sys.argv) > 2 else "top"
    max_pages = int(sys.argv[3]) if len(sys.argv) > 3 else 20  # about 15 comments a page
    out = "comments_" + re.sub(r"[^\w-]", "_", post) + ".csv"
    path = f"/v1/instagram/posts/{quote(post, safe='')}/comments"

    rows, calls, credits, error = 0, 0, 0, None
    with open(out, "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.DictWriter(f, fieldnames=FIELDS)
        writer.writeheader()
        try:
            for page in walk(path, {"sort": sort}, max_pages):
                calls += 1
                credits += page["meta"].get("credits_charged", 0)
                for c in page["data"]:
                    writer.writerow(row(c))
                    rows += 1
                    if c.get("reply_count", 0) > 0 and MAX_REPLY_PAGES > 0:
                        replies_path = f"/v1/instagram/comments/{c['id']}/replies"
                        for rpage in walk(replies_path, {"post": post}, MAX_REPLY_PAGES):
                            calls += 1
                            credits += rpage["meta"].get("credits_charged", 0)
                            for r in rpage["data"]:
                                writer.writerow(row(r, parent_id=c["id"]))
                                rows += 1
                print(f"{rows} comments and replies so far")
        except (ApiError, requests.RequestException) as e:
            error = e

    if error:
        sys.exit(f"Stopped: {error}\n{rows} rows saved in {out}")
    print(f"Saved {rows} rows to {out} ({calls} calls, {credits:g} credits)")


if __name__ == "__main__":
    main()
Tested 2026-12-02 against the documented API responses on Python 3.9.6. Run: python instagram_comments.py https://www.instagram.com/p/C9xYzAbCdEf/ newest

Run it

  1. Get an API key. Sign up at api.handlehaul.com/signup and create a key. A sandbox key (kd_test_) returns sample data for free while you test.
  2. Set HANDLEHAUL_API_KEY. Export the key as the environment variable HANDLEHAUL_API_KEY so it never sits in the code.
  3. Install requests. Run pip install requests. Python 3.9 or newer is required; everything else is in the standard library.
  4. Save the script as instagram_comments.py. Copy the script above into instagram_comments.py.
  5. Run it. Run python instagram_comments.py https://www.instagram.com/p/C9xYzAbCdEf/ newest. Progress prints as it goes; the output file is written as rows arrive, so an interrupted run keeps what it fetched.
Terminal
export HANDLEHAUL_API_KEY=kd_live_...   # your key from the dashboard
pip install requests
python instagram_comments.py https://www.instagram.com/p/C9xYzAbCdEf/ newest
On Windows PowerShell, set the key with $env:HANDLEHAUL_API_KEY="kd_live_...".

How it works

Paging. /v1/instagram/posts/{post}/comments returns about 15 comments a page. The script follows pagination.next_cursor until has_more is false or max_pages is reached (20 by default, so about 300 comments).

Sort. top (the default) or newest, passed as ?sort=. Use newest when you collect comments on a schedule and only need what is new.

Replies only where they exist. Each comment has a reply_count. Only when it is above zero does the script call /v1/instagram/comments/{comment}/replies with ?post= set to the shortcode, so you never pay for empty reply pages. MAX_REPLY_PAGES caps it per comment; set it to 0 to skip replies.

parent_id. The script fills this column with the id of the comment a reply answers, so you can rebuild threads in a spreadsheet. Top-level comments leave it empty.

Links work. Paste the post or reel link or just the shortcode; the script pulls the shortcode out of instagram.com/p/…, /reel/… and /tv/… links.

What it costs

Every successful call is 1 credit, at $1.40 to $0.80 per 1,000 calls. One call per page of about 15 comments, plus one call per page of replies for each comment that has replies. Failed calls and private accounts are free.

Calls and cost for export instagram comments to csv
JobCallsCost
100 comments7$0.0098 to $0.0056
1,000 comments67$0.094 to $0.054
10,000 comments667$0.93 to $0.53

The script makes one call at a time, well under the account limit of 10 to 30 requests per second. Each response says what it cost in meta.credits_charged, and the script adds those up in its last line.

Sample output

An example run with example values, not a real export. Field names and shapes are the ones in the API docs.

Terminal
16 comments and replies so far
31 comments and replies so far
46 comments and replies so far
Saved 46 rows to comments_C9xYzAbCdEf.csv (4 calls, 4 credits)
comments_C9xYzAbCdEf.csv
id,parent_id,created_at,username,full_name,like_count,reply_count,text
782890015575457736,,2026-11-28T12:00:00.000Z,studio.atelier21,Studio Atelier,76,0,Love this!
782890015575457801,,2026-11-28T12:04:00.000Z,coffee.place,Coffee Place,12,1,"Where was this, Lisbon?"
782890015575457950,782890015575457801,2026-11-28T12:30:00.000Z,studio.atelier21,Studio Atelier,3,0,Yes!

Common errors

Errors come back as { "error": { "code", "message", "request_id" } } with an HTTP status. Failed calls are never charged. Full list: error codes.

Errors this script can meet and what it does
Status and codeWhenWhat the script does
403 private_accountThe post belongs to a private accountStops. Free.
404The post does not exist or was deletedStops. Free. Check the shortcode.
400 invalid_cursorA cursor from another postStops. Start again without a cursor.
401 invalid_api_keyThe key is missing, wrong or revokedStops with the message. Check the variable with echo $HANDLEHAUL_API_KEY.
402 insufficient_creditsThe account is out of creditsStops. Rows already fetched stay in the file.
429 rate_limitedToo many requests per secondWaits for Retry-After and retries, up to 5 times. Not charged.
502 / 503 / 504Data temporarily unavailable or slowRetries with a growing wait (1, 2, 4, 8, 16 s). Failed calls are free.

The same job with the SDK

If you would rather not maintain the HTTP code, the official Python SDK (pip install handlehaul) does the paging, retries 429 for you and raises typed errors. The script above is the same job with every request visible.

Python SDK
# pip install handlehaul
from handlehaul import HandleHaul

hh = HandleHaul()  # reads HANDLEHAUL_API_KEY
for c in hh.instagram.post_comments.iterate("C9xYzAbCdEf", sort="newest", max_pages=20):
    print(c["author"]["username"], c["like_count"], c["text"])
Source and reference: handlehaul-python on GitHub.

Next steps

Export Instagram comments to CSV with Python: questions

How do I scrape all comments from an Instagram post?
Raise the page limit, for example python instagram_comments.py C9xYzAbCdEf top 200. The script stops by itself when has_more is false.
What is the difference between top and newest?
top is Instagram’s default ranking, newest is newest first. For a one-off export either works; for checking a post every day, newest lets you stop as soon as you reach comments you already have.
Can I get who liked a comment?
Yes, with /v1/instagram/comments/{comment}/likers, one call per page. The script does not do it, to keep the cost to comments and replies only.
Can I analyse the comments with pandas or an LLM?
Yes. pd.read_csv() reads the file as is, and the text column is ready for sentiment analysis or summarising. Keep the id column so you can de-duplicate when you re-run.

Run it on your own list

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.