Instagram posts scraper: an account's posts to CSV

This Python script saves a public Instagram account's posts to a CSV file. You get up to 12 posts a call at $0.0020, so 120 posts cost $0.0200 or more. To get only reels, change one setting. A failed call is not charged.

Updated 2026-11-29Open in ChatGPTOpen in Claude

The endpoint's page covers a single request. Here you get page after page of posts in one file, up to a limit you set, and what to check before you compare accounts.

What one real run got

Run on 2026-11-29, exactly as printed below. UNICEF's account (unicef): all kinds of posts, 10 calls. It made 10 calls, wrote 120 rows and cost $0.0200. There was more to get when it stopped.

id,url,published_at,type,caption,likes,comments,views
Df-4mLTEQ1S,https://www.instagram.com/p/Df-4mLTEQ1S/,2026-11-21T00:01:17.000Z,video,"Eighty years of progress, not by chance but by choice. Watch as…",1287,21,66300
DgC-FP4l7vV,https://www.instagram.com/p/DgC-FP4l7vV/,2026-11-22T14:00:25.000Z,image,Safety. Freedom. Hope. This is the future five-year-old Ruth…,2533,44,
Df1ITT2l11G,https://www.instagram.com/p/Df1ITT2l11G/,2026-11-17T05:00:20.000Z,image,Repeat after us: Children’s rights are human rights. This…,16067,136,

Rows from the file it wrote. Long text is cut short here; the file has all of it.

The whole script

Save this as export.py and change the settings at the top. Install the SDK, set your key as the first two lines show, then run python3 export.py. You need Python 3.9 or later. The CSV file is saved in the folder you run it from. At the end, the script shows how many calls it made, how many rows it wrote and what was charged.

Python
# Python 3.9 or later. First: python3 -m pip install dataxapi
# and: export DATAXAPI_API_KEY=dx_...   (your key)
import csv
import sys
from decimal import Decimal
from dataxapi import APIConnectionError, DataXAPI, DataXAPIError

ACCOUNT = "unicef"      # the handle, without the @
KIND = "all"            # "all", or "reel" for reels only
MAX_CALLS = 10          # up to 12 posts a call; the run stops here
OUT = "instagram_posts.csv"   # a new file: the run won't replace one
SHEET_SAFE = True       # puts ' before text a spreadsheet could run as a formula; False keeps it as it is

dx = DataXAPI()
calls, charged, seen, more, problem = 0, Decimal("0"), set(), False, None

class OutOfCalls(Exception):
    pass

def call(capability, params):
    """One call, never more than MAX_CALLS of them, failed ones included; adds up what they were charged."""
    global calls, charged
    if calls >= MAX_CALLS:
        raise OutOfCalls
    calls += 1
    result = dx.call(capability, params)
    charged += Decimal(str(result["meta"]["billing"]["amount"]))
    return result

def cell(value):
    """Text that begins as a formula does gets a ' before it, so a spreadsheet shows it and does not run it."""
    if SHEET_SAFE and isinstance(value, str) and value.lstrip(" ").startswith(("=", "+", "-", "@", "\t", "\r", "\n", "=", "+", "-", "@")):
        return "'" + value
    return value

def pages(capability, params, most=None):
    """The items of each page, to the last one or to `most` pages; `more` turns true when some are left."""
    global more
    cursor, count = None, 0
    while True:
        result = call(capability, {**params, **({"cursor": cursor} if cursor else {})})
        yield result["data"]["items"]
        count += 1
        if not result["page"]["has_more"]:
            return
        if most is not None and count >= most:
            more = True
            return
        cursor = result["page"]["next_cursor"]

with open(OUT, "x", newline="", encoding="utf-8") as file:
    out = csv.writer(file)
    out.writerow(["id", "url", "published_at", "type", "caption", "likes", "comments", "views"])
    try:
        for items in pages("instagram.users.posts.list", {"username": ACCOUNT, "type": KIND}):
            for item in items:
                if item["id"] in seen:
                    continue
                metrics = item.get("metrics") or {}
                out.writerow([cell(item["id"]), item["url"], item.get("published_at"), item.get("type"), cell(item.get("text")), metrics.get("likes"), metrics.get("comments"), metrics.get("views")])
                seen.add(item["id"])
            file.flush()
    except OutOfCalls:
        more = True
    except (DataXAPIError, APIConnectionError) as error:
        problem = error

print(f"calls: {calls}, rows: {len(seen)}, charged: ${charged}" + (", and there is more to get" if more else ""))
if problem:
    print(f"Stopped by an error; the rows above are saved. {problem}")
    if problem.unsettled:
        print("The last call may have been charged. Check your call history before you run this again.")
    sys.exit(1)

Open the file safely

Anyone can start a comment, caption or bio with =, +, - or @, and a spreadsheet may run it as a formula. SHEET_SAFE puts ' before text like that. If you set it to False, don't open the file by double-clicking it. Some IDs are long numbers, which a spreadsheet may round. To keep them exact, use its CSV import and set the ID, handle and text columns to Text.

If it stops early

MAX_CALLS counts every call, including failed ones. If the SDK tries a call again, it still counts as one. If a call fails, the script stops, keeps the rows it has and shows what it knows was charged. If the connection drops before an answer arrives, that call may still have been charged. The script tells you, so check your call history before you run it again. It never replaces a file: for another run, change OUT or move the old file.

What it costs

JobCallsCost
120 posts10$0.0200
1,200 posts100$0.20
The first page of posts from each of 100 accounts100$0.20

These numbers assume 12 posts on every page. The script does one account at a time. To compare accounts, use posts from the same dates: likes and views keep growing after a post goes up. Prices are the ones in force when this page was built.

What is in the file

ColumnWhat it is
idThe post's short code, as in its link
urlIts link
published_atWhen it was posted, in UTC
typeimage or video; a post with several pictures can be an image
captionIts caption
likesIts likes
commentsHow many comments it has
viewsA video's plays; empty for images

How it works

  1. Put the account's handle in ACCOUNT, without the @. Set KIND to reel to get only reels.
  2. Each call gets up to 12 posts, in the order the list gives them. The script stops at the last page or at MAX_CALLS.
  3. If a post appears twice, the script writes it once.

What to know first

  • Image posts have no view count, so views is empty for them. Don't count an empty value as zero when you work out an average.
  • The first posts aren't always the newest: pinned posts can come first. You can sort the file by published_at, but that won't add posts the run didn't reach.
  • A post published together with another account can be in this account's list too.
  • This only works for public accounts. Check the handle with the profile endpoint first. With all, a handle that doesn't exist looks like an account with no posts: you get only the column names. With reel, it stops with an error that isn't charged.
  • A run starts from the first page. It can't pick up where an earlier run stopped, because the cursor for the next page works for an hour and isn't saved.

Or ask your AI

With DataXAPI connected over MCP, say: Save up to 120 posts from UNICEF's Instagram account to a CSV with likes, comments and views. Tell me the price first and stop at 10 calls.