Facebook comment scraper: recent posts to CSV
This Python script saves the comments on up to three recent posts from a Facebook page to a CSV file. You get up to 10 comments a call at $0.0020. With full pages, 1,000 comments and the call that finds the posts cost $0.202. A failed call is not charged.
The endpoint's page covers a single request. Here you get the posts' IDs found for you, your calls shared between several posts, and one file without names.
What one real run got
Run on 2026-11-29, exactly as printed below. The first three posts in the list for NASA's page (NASA): one call to find them and 19 for their comments, taken in turn. It made 20 calls, wrote 190 rows and cost $0.0400. There was more to get when it stopped.
id,post_id,published_at,text,reactions,replies [ID],[post ID],2026-11-27T18:52:44.000Z,[comment text],7,0 [ID],[post ID],2026-11-28T00:40:06.000Z,[comment text],7,0 [ID],[post ID],2026-11-27T20:36:49.000Z,[comment text],9,2
Rows from the file it wrote. Comment text and IDs are left out here; the file has them.
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 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 page whose first listed posts are read POSTS = 3 # how many of them: 1, 2 or 3 MAX_CALLS = 20 # the run stops here, whatever is left OUT = "facebook_comments.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 with open(OUT, "x", newline="", encoding="utf-8") as file: out = csv.writer(file) out.writerow(["id", "post_id", "published_at", "text", "reactions", "replies"]) try: # 1. The first posts the page's list gives, for their IDs. Have the IDs already? Put them in `posts` instead. posts = [item["id"] for item in call("facebook.pages.posts.list", {"username": PAGE})["data"]["items"]][:POSTS] # 2. One page of comments from each post in turn, until every post is done or the calls run out. A post that # is done leaves its calls to the others, and a busy one can't use them all. left = {post: None for post in posts} while left: for post, cursor in list(left.items()): result = call("facebook.posts.comments.list", {"id": post, **({"cursor": cursor} if cursor else {})}) for item in result["data"]["items"]: if item["id"] in seen: continue metrics = item.get("metrics") or {} out.writerow([cell(item["id"]), post, item.get("published_at"), cell(item["text"]), metrics.get("likes"), metrics.get("comments")]) seen.add(item["id"]) file.flush() if result["page"]["has_more"]: left[post] = result["page"]["next_cursor"] else: del left[post] 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
These numbers assume 10 comments on every page. Some pages have fewer, so the same number of comments can take more calls. Prices are the ones in force when this page was built.
What is in the file
idThe comment's IDpost_idThe post it is onpublished_atWhen it was posted, in UTCtextWhat it says; may be emptyreactionsAll reactions together: like, love, haha and the restrepliesHow many replies it has; the replies themselves aren't includedHow it works
- Put the page's handle in
PAGE. The script first gets the first posts in the page's list because the comments endpoint needs each post's numericid. That is one call, and it counts towardMAX_CALLS. If you already have the IDs the API gives, put them inpostsand skip that call. The code in a post's link isn't always that ID. - It gets one page of comments from each post in turn. When it has them all for one post, the calls left go to the other posts.
- If a comment appears twice, the script writes it once. At the end, it says if there were more comments to get.
What to know first
- You get comments, but not the replies under them. The
repliescolumn shows how many replies there are. - You get public comments only, and can get fewer than the number on the post.
- The file doesn't include names, but the words of a comment and its ID can still point to a person. Keep only what you need, and remove both before you share the file.
- 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.