Facebook posts scraper: export a page's posts to CSV

This Python script saves a public Facebook page's posts to a CSV file. You get up to 3 posts a call at $0.0020, so 300 posts take at least 100 calls and cost $0.20 or more. 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 30, 300 and 1,000 posts cost.

What one real run got

Run on 2026-11-29, exactly as printed below. NASA's page (NASA): 20 calls, starting with its newest posts. It made 20 calls, wrote 60 rows and cost $0.0400. There was more to get when it stopped.

id,url,published_at,type,text,reactions,comments
1700684364760266,https://www.facebook.com/NASA/posts/pfbid02VgGt2ndMVuWJ9HAZFdTkfNvD…,2026-11-27T17:09:23.000Z,image,It's like looking in a mirror… 🤩 This barred galaxy in the…,6394,243
1697460178416018,https://www.facebook.com/NASA/posts/pfbid02sh3rQBEX55F1HwAtiWs5oTw9…,2026-11-24T16:50:00.000Z,image,"A home away from home 🌕 We're building a Moon Base, where…",2796,239
1696522545176448,https://www.facebook.com/reel/2688015701636592/,2026-11-23T19:00:45.000Z,video,Happy Thanksgiving from the International Space Station! NASA…,5589,309

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

PAGE = "NASA"           # the part of the page's link after facebook.com/
MAX_CALLS = 20          # up to 3 posts a call; the run stops here
OUT = "facebook_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", "text", "reactions", "comments"])
    try:
        for items in pages("facebook.pages.posts.list", {"username": PAGE}):
            for item in items:
                if item["id"] in seen:
                    continue
                metrics = item.get("metrics") or {}
                out.writerow([item["id"], item["url"], item.get("published_at"), item.get("type"), cell(item.get("text")), metrics.get("likes"), metrics.get("comments")])
                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
30 posts10$0.0200
300 posts100$0.20
1,000 posts334$0.668

These numbers assume 3 posts on every page. The script doesn't know what an earlier run got: if you run it again, you pay for those posts again. Prices are the ones in force when this page was built.

What is in the file

ColumnWhat it is
idThe post's ID
urlIts link
published_atWhen it was posted, in UTC
typeimage, video or text
textWhat it says; empty when the post has no text
reactionsAll reactions together: like, love, haha and the rest
commentsHow many comments it has

How it works

  1. Put the page's handle in PAGE: it is the part after facebook.com/ in its link. A numeric page ID also works: replace username with id.
  2. Each call gets up to 3 posts. The script follows the list to its last page, or until it reaches MAX_CALLS. In the run above, every post was older than the one before it. To be sure of the order, sort your file by published_at.
  3. If a post appears twice, the script writes it once.

What to know first

  • Shares and video views aren't in the list. Use the Facebook post endpoint to get them, one call for each post.
  • It works for public pages, not personal profiles, private groups or anything you need to sign in to see.
  • 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 the 60 newest posts on NASA's Facebook page to a CSV with their reactions and comment counts. Tell me the price first and stop at 20 calls.