Social Media Scraper

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.

Editorial illustration showing a code editor and ad cards connected to a saved JSON snapshot archive
Illustration of code saving JSON snapshots

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.

  1. CLI query and env key
  2. GET adlibrary_search_ads
  3. Saved JSON snapshot
Workflow from command-line query and API key to a saved JSON snapshot file

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.

how-to-build-a-facebook-ad-spy-tool.py
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.

Snapshot JSON structure and field types
{
  "query": "string",
  "fetched_at": "string",
  "data": {
    "items": [
      {
        "id": "string",
        "title": "string | null",
        "text": "string | null",
        "url": "string | null"
      }
    ]
  }
}
Example field schema for a saved JSON snapshot, not an actual query result.

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?

Read the API documentation →

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.