Python project guide
How to Build a Facebook Ad Spy Tool with Python
Python developers can query Social Media Scraper's Facebook Ad Library endpoint to build a lightweight Facebook ad spy tool that saves available public ad copy and links as JSON. Configure your API key in your terminal environment to write structured search results to a local file.

What Does a Python Ad Library Script Save?
The script calls the Facebook Ad Library API once per run and saves your search query, a UTC fetched_at timestamp, and returned public records in a JSON file. It uses Python standard-library modules so you can inspect the saved output directly.
Query and run timestamp
Save the search query and UTC fetched_at timestamp together so every JSON file shows when you collected those records.
Returned ad fields
Save available public ad text, IDs, and links while leaving missing fields absent or null.
New JSON file per run
Write results to the --out path and stop if that file already exists so earlier captures stay intact.
Why Save Public Ad Records for Research?
Public ads and destination links change over time, so saving JSON snapshots lets you review exact copy and URLs later. Teams doing competitor ad research can revisit captured records without relying on memory or manual screenshots.
Keep exact ad copy and links
Save returned text, titles, and source URLs from each search so you can check the exact wording later.
Inspect JSON records in code
Read saved JSON files in Python or pull selected fields into your notes and research sheets.
Revisit dated captures
Open a specific snapshot file later to verify what appeared during that earlier search.
How Do You Run the Script and Save JSON?
Set SOCIALSCRAPER_API_KEY in your environment, run the Python script with a search query and --out path, and read the saved JSON file. Each run sends one GET request without retries and exits if --out already exists.
- CLI query and env key
- GET adlibrary_search_ads
- Saved JSON snapshot
Load the API key
Read SOCIALSCRAPER_API_KEY from your shell environment and send it in the x-api-key header.
Search with one GET request
Pass your query to the script to call the Facebook Ad Library search endpoint once over HTTP.
Write the JSON snapshot
Save query, fetched_at, and returned data to the --out JSON file, then open it to inspect the fields.
How Do You Run the Python Snapshot Script?
Set SOCIALSCRAPER_API_KEY, then run the script with a query and an --out JSON path. It makes one GET request, saves query, fetched_at, and returned data, and stops if the output file already exists.
import argparse
import datetime
import json
import os
import pathlib
import urllib.error
import urllib.parse
import urllib.request
import uuid
ORIGIN = "https://socialmediascraper.org"
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
def fetch(operation, params):
key = os.environ.get("SOCIALSCRAPER_API_KEY")
if not key:
raise SystemExit("Set SOCIALSCRAPER_API_KEY in your environment first.")
url = ORIGIN + "/v1/" + operation.replace(".", "/")
request = urllib.request.Request(url + "?" + urllib.parse.urlencode(params), headers={
"x-api-key": key,
"Idempotency-Key": str(uuid.uuid4()),
"Accept": "application/json",
"User-Agent": "SocialMediaScraperTutorial/1.0",
})
try:
with urllib.request.build_opener(NoRedirect()).open(request, timeout=40) as response:
payload = json.load(response)
except urllib.error.HTTPError as error:
raise SystemExit("Request stopped with HTTP " + str(error.code)) from None
except (OSError, ValueError):
raise SystemExit("Request failed; inspect the saved request status before retrying.") from None
data = payload.get("data")
if not isinstance(data, dict):
raise SystemExit("No data object returned; inspect the API response contract.")
return data
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--out", default="research-output")
args = parser.parse_args()
destination = pathlib.Path(args.out)
if destination.exists() or destination.with_suffix(".json").exists():
raise SystemExit("Output exists. Choose another --out before starting a new billed request.")
destination.parent.mkdir(parents=True, exist_ok=True)
data = fetch("facebook.adlibrary_search_ads", {"query": args.input})
snapshot = {"query": args.input, "fetched_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "data": data}
destination.with_suffix(".json").write_text(json.dumps(snapshot, ensure_ascii=False, indent=2), encoding="utf-8")
print(destination.with_suffix(".json"))
Copy or download the request, Python script, or n8n workflow, then run it in your own environment with an active API key and balance.
How Do You Compare Saved Ad Snapshots?
Compare public ad IDs, text, and URLs across two saved JSON files from different runs. Any difference reflects what appeared in those two captures, not a full archive or guaranteed ad change.
Compare IDs, text, and URLs
Match ad IDs, copy, and links between two JSON files to see which records changed across runs.
Check missing fields carefully
Treat a missing field or absent record in a later run as unreturned in that capture, not proof of removal.
Compare only saved runs
Check differences between your own JSON snapshots rather than assuming complete historical coverage.
{
"query": "string",
"fetched_at": "string",
"data": {
"items": [
{
"id": "string",
"title": "string | null",
"text": "string | null",
"url": "string | null"
}
]
}
}Who Uses Saved Ad Records for Creative Briefs?
Marketers, copywriters, and builders use saved public ad archives to group hooks, offers, and formats before drafting creative briefs. You can pass the JSON output into your own script, spreadsheet, or prompt step for tagging or summaries.
Group hooks and offers
Sort saved public ad copy and links by angle or offer to shape questions for creative briefs.
Compare creative formats
Review returned ad fields across public records to see how teams structure headlines and calls to action.
Share snapshots for review
Export selected fields or pass JSON files to teammates before writing briefs or building downstream steps.
Why Can Public Ad Data Not Prove Performance?
Public ad records do not include private ad spend, conversions, or full targeting settings. How long an ad appears across snapshots does not show whether a campaign is profitable or driving sales.
No spend or conversion metrics
Public ad library responses do not return ad spend, return on ad spend, or conversion counts.
Age does not mean profit
An ad appearing across multiple runs is not proof of profit, since teams pause or run tests for many reasons.
No media or page crawling
Search results do not download media files, crawl landing pages, or guarantee complete platform coverage.
How Should You Handle Ad Snapshot Files?
Start from the standard-library Python script, set SOCIALSCRAPER_API_KEY in your environment, and pass a query and --out path on the command line to save public ad records as JSON.
Run the Python script with a search query and --out file path so it writes query, fetched_at, and returned data into a JSON file on disk.
Load two saved JSON snapshots in a short Python script or spreadsheet and compare their ad IDs, text fields, and URLs while treating missing fields as absent in that capture.
No, repeated appearances only show the ad showed up in those captures, not that it generated profit or conversions.
Free browser searches allow three shared anonymous runs per network per UTC day, while script runs use SOCIALSCRAPER_API_KEY and your account balance.
Read the saved JSON file in your own script, spreadsheet, or scheduled job after checking the output; public ad collection does not publish ads or manage campaigns.
When Should You Try the Tool or Check Docs?
Run a search in the browser tool first or check the endpoint parameters before running the Python script.