# Facebook Ad Library Scraper (`melodious_momentum/facebook-ad-library-scraper`) Actor

Scrape the Facebook Ad Library from pasted URLs. Returns the full ad object (curious\_coder-compatible superset) including EU + UK transparency, advertiser, and reach breakdowns. Uses Apify Residential proxy with automatic rotation on rate-limits.

- **URL**: https://apify.com/melodious\_momentum/facebook-ad-library-scraper.md
- **Developed by:** [Eugenerio](https://apify.com/melodious_momentum) (community)
- **Categories:** Social media, Automation, Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Facebook Ad Library Scraper

A Python + [Scrapling](https://github.com/D4Vinci/Scrapling) scraper for the **Facebook Ad Library**, packaged as an **Apify actor**. Paste Ad Library URLs → get the full ad object (a **superset of [`curious_coder/facebook-ads-library-scraper`](https://apify.com/curious_coder/facebook-ads-library-scraper)**), including EU **and** UK transparency, advertiser info, and per-country age/gender reach breakdowns.

> **Drop-in replacement for `curious_coder/facebook-ads-library-scraper`.** Same input fields,
> same output records in the same field order (plus a couple of extra fields). To switch an
> existing integration, see **[MIGRATION.md](./MIGRATION.md)** — usually just changing the actor id.
>
> - Actor: `concrete_pavilion/facebook-ad-library-scraper` · ID `VPPuOei1FoCdSE815`

### How it works

Facebook's public Ad Library is a React SPA that loads ads via an internal GraphQL API. This scraper uses a **"bootstrap → replay"** strategy:

1. **Bootstrap (no browser)** — a plain HTTP GET of the search URL (`http_bootstrap.py`) returns the session tokens (`lsd`, `jazoest`, `__*`) **and the server-rendered first page of ads** embedded in the HTML. This avoids launching a stealth browser (which downloads ~40 MB of ad-creative video/images through the proxy) — cutting residential bandwidth **~25–50×** and running ~8× faster. A media-blocked stealth browser (`bootstrap.py`) is kept as a fallback.
2. **Replay** — a fast HTTP client (Scrapling `Fetcher`, curl\_cffi with TLS-impersonation) replays the `AdLibrarySearchPaginationQuery` GraphQL POST, mutating only the pagination `cursor`, until every ad is collected.
3. **Details** (optional) — for each ad, `AdLibraryV3AdDetailsQuery` returns `advertiser`, `aaa_info`, and full `transparency_by_location` (EU + UK reach breakdowns), merged losslessly. Detail queries are fetched **concurrently** (`detailsConcurrency`, default 15 on the actor).

Each output record is then arranged to **curious\_coder's exact field order** at every nesting level (see `reorder.py` / `_order_template.json`); our extra fields are appended, never substituted.

Facebook rate-limits by IP (error `1675004`); with a `proxy_provider` (Apify Residential) the scraper **rotates to a fresh IP** and continues.

Works **logged-out**. Only two GraphQL queries are needed:

| Query | doc\_id | Purpose |
|---|---|---|
| `AdLibrarySearchPaginationQuery` | `24922295957467452` | The ad list (cursor pagination) |
| `AdLibraryV3AdDetailsQuery` | `25068828942793558` | Per-ad detail (`--scrape-ad-details`) |

Facebook rate-limits aggressively (error code `1675004`), so the scraper supports **proxy rotation**: on a rate-limit it rotates to a fresh IP (Apify residential) and continues.

### Install (local)

Requires Python 3.11+ and [uv](https://github.com/astral-sh/uv) (or plain pip).

```bash
uv venv --python 3.11 .venv
uv pip install --python .venv/bin/python -e ".[dev]"
.venv/bin/scrapling install        # downloads the stealth browser (patchright chromium)
```

### CLI usage

```bash
.venv/bin/fb-ads-scrape \
  --url 'https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&media_type=all&q=nike&search_type=keyword_unordered&sort_data[mode]=total_impressions&sort_data[direction]=desc' \
  --scrape-ad-details \
  --limit-per-source 50 \
  --proxy 'http://user:pass@host:port' \
  --out ads.jsonl
```

Options: `--url` (repeatable), `--out` (`.jsonl`/`.json`/`.csv`), `--count`, `--limit-per-source`, `--scrape-ad-details`, `--active-status`, `--country`, `--proxy`, `--run-tag`. With no `--count`/`--limit-per-source`, it scrapes **all** ads for the query.

### Python API

```python
from fb_ads_scraper.models import ScrapeOptions
from fb_ads_scraper.runner import scrape

opts = ScrapeOptions(urls=["https://www.facebook.com/ads/library/?q=nike&search_type=keyword_unordered"],
                     scrapeAdDetails=True, limitPerSource=50)
for ad in scrape(opts, proxy_provider=lambda: "http://user:pass@host:port"):
    print(ad["ad_archive_id"], ad.get("aaa_info", {}).get("eu_total_reach"))
```

### Apify actor

The `.actor/` directory + `src/main.py` wrap the package as an Apify actor (`concrete_pavilion/facebook-ad-library-scraper`, ID `VPPuOei1FoCdSE815`) with **Apify Residential proxy + rotation** built in.

```bash
apify login                 # once
apify run                   # local run; reads storage/key_value_stores/default/INPUT.json
apify push                  # deploy to the Apify platform (use --force to overwrite console edits)
```

Input (see `.actor/input_schema.json`): `urls`, `scrapeAdDetails`, `count`, `limitPerSource`, `maxConcurrency`, `detailsConcurrency`, `scrapePageAds.{period,activeStatus,sortBy,countryCode}`, `runTag`, `proxyConfiguration` (defaults to RESIDENTIAL — also accepts curious\_coder's `proxy` field name). Each ad is pushed to the default dataset.

- **Memory:** default **1024 MB** (0.25 vCPU) — this is I/O-bound and uses ~120 MB; Apify bills memory × time, so it's right-sized for cost.
- **Logs:** a startup banner, per-URL progress at ~10% milestones (`▶ … N ads available` → `k/N ads (Xs, R ads/s)` → `✓ … N ads in Mm SSs`), and a final run summary. Scrapling's per-request noise is suppressed.

### Output

The raw Facebook ad node (lossless) plus enrichments — arranged to curious\_coder's exact field order: `url`, `ad_library_url`, `start_date_formatted`, `end_date_formatted`, 1-based `position`, `total` (actual ads returned for the URL), `ads_count`, stringified `page_id`, and (with `scrapeAdDetails`) `advertiser`, `aaa_info`, `transparency_by_location.{eu_transparency, uk_transparency, br_transparency}`, `verified_voice_context`. The one field we add beyond curious\_coder is `is_siep_advertiser_eligible_for_ai_disclosure`. See **[MIGRATION.md](./MIGRATION.md)** for the full compatibility contract and `docs/superpowers/specs/` for the schema + a real captured example.

### Testing

```bash
.venv/bin/pytest -q            # unit tests (no network)
.venv/bin/pytest -m network    # opt-in live tests (need a proxy or a cooled-down IP)
```

### Project layout

```
fb_ads_scraper/     # the scraper package
  url_parser.py     # Ad Library URL -> GraphQL variables
  bootstrap.py      # stealth-browser token/session capture
  client.py         # curl_cffi GraphQL replay
  paginator.py      # cursor pagination + rate-limit backoff/rotation
  extractor.py      # pull ad nodes from GraphQL payloads
  details.py        # AdLibraryV3AdDetailsQuery enrichment (EU/UK transparency)
  normalizer.py     # superset output + enrichments (calls reorder)
  reorder.py        # re-key each ad to curious_coder's field order (+ _order_template.json)
  session.py        # captured-request -> replay form builder
  proxies.py        # ProxyRotator
  runner.py         # orchestration across URLs (+ proxy rotation, progress logs)
  output.py, cli.py, models.py
src/                # Apify actor entrypoint (main.py)
.actor/             # actor.json (memory 1024 MB), input_schema.json, Dockerfile
tests/              # pytest suite + real captured fixtures
docs/superpowers/   # design spec, implementation plan, live capture reference
MIGRATION.md        # drop-in migration guide from curious_coder's actor
```

### Notes & compliance

Scraping Facebook is against its Terms of Service — treat this as a legal/compliance decision, not just a technical one. Use residential proxies and reasonable pacing.

# Actor input Schema

## `urls` (type: `array`):

Facebook Ad Library search or page URLs to scrape (keyword search, view-all-page, date-filtered — any facebook.com/ads/library/ URL).

## `scrapeAdDetails` (type: `boolean`):

Fetch the full per-ad detail: advertiser (page info, page spend), aaa\_info, and EU + UK transparency (reach + age/gender/country breakdowns). Adds one request per ad.

## `count` (type: `integer`):

Maximum ads across all URLs. Leave empty to scrape everything.

## `limitPerSource` (type: `integer`):

Cap the number of ads scraped per input URL. Leave empty to scrape all available ads.

## `maxConcurrency` (type: `integer`):

How many input URLs to scrape in parallel (each gets its own proxy session). 1 = sequential.

## `detailsConcurrency` (type: `integer`):

How many per-ad detail queries to fetch in parallel (only when 'Scrape ad details' is on). Each uses a fresh residential IP, so higher is safe.

## `scrapePageAds.activeStatus` (type: `string`):

Filter by ad status (fills in when the URL doesn't specify it).

## `scrapePageAds.countryCode` (type: `string`):

2-letter ISO country code, or ALL. Fills in when the URL doesn't specify it.

## `scrapePageAds.period` (type: `string`):

Only ads that ran in this window (adds a start-date filter when the URL has none).

## `scrapePageAds.sortBy` (type: `string`):

Sort order (used when the URL has no sort).

## `runTag` (type: `string`):

Optional value copied into a 'runTag' field on every output record.

## `proxyConfiguration` (type: `object`):

Apify Proxy. RESIDENTIAL is strongly recommended — Facebook blocks datacenter IPs and rate-limits quickly. Country is optional (auto by default).

## Actor input object example

```json
{
  "urls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&media_type=all&q=riseguide.com&search_type=keyword_unordered&sort_data[mode]=total_impressions&sort_data[direction]=desc"
    }
  ],
  "scrapeAdDetails": false,
  "maxConcurrency": 4,
  "detailsConcurrency": 10,
  "scrapePageAds.activeStatus": "all",
  "scrapePageAds.countryCode": "ALL",
  "scrapePageAds.period": "",
  "scrapePageAds.sortBy": "impressions_desc",
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}
```

# Actor output Schema

## `ads` (type: `string`):

Every ad collected from the input Ad Library URLs: the full ad object (snapshot creative, dates, platforms, categories) plus `url`, `ad_library_url`, `position`, `total`, and — when 'Scrape ad details' is on — `advertiser`, `aaa_info`, and EU/UK `transparency_by_location`.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "urls": [
        {
            "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&media_type=all&q=riseguide.com&search_type=keyword_unordered&sort_data[mode]=total_impressions&sort_data[direction]=desc"
        }
    ],
    "proxyConfiguration": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("melodious_momentum/facebook-ad-library-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "urls": [{ "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&media_type=all&q=riseguide.com&search_type=keyword_unordered&sort_data[mode]=total_impressions&sort_data[direction]=desc" }],
    "proxyConfiguration": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
    },
}

# Run the Actor and wait for it to finish
run = client.actor("melodious_momentum/facebook-ad-library-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "urls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&media_type=all&q=riseguide.com&search_type=keyword_unordered&sort_data[mode]=total_impressions&sort_data[direction]=desc"
    }
  ],
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}' |
apify call melodious_momentum/facebook-ad-library-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,melodious_momentum/facebook-ad-library-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/FDOLpxB91mEpeXI1E/builds/wdbROgigG4TCAS15d/openapi.json
