# Facebook Ad Library Scraper Pro (`kalirobot/fb-ad-library-scraper`) Actor

Fast & reliable Facebook Ad Library scraper. Extract ads by keyword or page with smart fallback search. Get creative, targeting, metrics & media. Multi-country support. Perfect for competitor analysis & ad intelligence.

- **URL**: https://apify.com/kalirobot/fb-ad-library-scraper.md
- **Developed by:** [Dennis](https://apify.com/kalirobot) (community)
- **Categories:** Social media, Lead generation, Developer tools
- **Stats:** 118 total users, 7 monthly users, 100.0% runs succeeded, 4 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

$0.75 / 1,000 ads

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/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Facebook Ad Library Scraper 2.0

A powerful Apify actor that scrapes ads from the Facebook Ad Library with advanced features like country selection, active status filtering, and intelligent fallback search.

### Features

- ✅ **Multi-Country Support**: Scrape ads from 247+ countries
- ✅ **Three Search Modes**: Keyword search, first suggestion, or direct Facebook URL/page ID
- ✅ **Flexible Input**: Mix and match URLs, page IDs, and keywords in bulk
- ✅ **Smart Fallback Search**: Automatically finds similar pages when keyword search returns no results
- ✅ **Duplicate Detection**: Prevents duplicate ads using ad\_id tracking
- ✅ **Active Status Filtering**: Filter by ALL, ACTIVE, or INACTIVE ads
- ✅ **Rich Data Extraction**: Extracts carousel cards, videos, images, and targeting info
- ✅ **Real-time Data Push**: Ads are saved immediately as they're found
- ✅ **Residential Proxy Support**: Works with Apify's residential proxies for reliable scraping

### Search Modes

#### 1. Keyword Search (Default)

Standard keyword search with intelligent fallback:

```json
{
  "searchTerms": ["Nike", "Adidas"],
  "searchMode": "keyword",
  "countryCode": "US",
  "maxAds": 100
}
```

#### 2. First Suggestion (Smart)

Uses first Typeahead API suggestion - perfect for brand pages:

```json
{
  "searchTerms": ["Tesla", "SpaceX"],
  "searchMode": "first_suggestion",
  "countryCode": "DE",
  "maxAds": 50
}
```

#### 3. Facebook URL/ID Direct

Fastest method - scrape directly from page URLs or IDs:

```json
{
  "searchTerms": [
    "https://www.facebook.com/UnderArmour",
    "8741241286",
    "https://www.facebook.com/Nike",
    "15087023444"
  ],
  "searchMode": "facebook_url",
  "countryCode": "US",
  "maxAds": 200
}
```

**Note:** You can mix URLs and page IDs in the same array for bulk scraping!

### Input Parameters

```json
{
  "searchTerms": ["Nike", "marketing"],
  "searchMode": "keyword",
  "countryCode": "DE",
  "adActiveStatus": "ACTIVE",
  "maxAds": 200,
  "enableSimilarSearch": true,
  "maxSimilarPages": 3,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": ["RESIDENTIAL"]
  }
}
```

#### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `searchTerms` | Array | **Required** | Keywords, page names, Facebook URLs, or page IDs |
| `searchMode` | String | `"keyword"` | How to search: "keyword", "first\_suggestion", or "facebook\_url" |
| `countryCode` | String | `"ALL"` | ISO 2-letter country code or "ALL" for all countries |
| `adActiveStatus` | String | `"ALL"` | Filter by ad status: "ALL", "ACTIVE", or "INACTIVE" |
| `maxAds` | Integer | `100` | Maximum number of ads to scrape per search term (1-5000) |
| `enableSimilarSearch` | Boolean | `true` | Enable fallback to similar pages when keyword returns no results |
| `maxSimilarPages` | Integer | `1` | Number of similar pages to try (1-5) |
| `debugMode` | Boolean | `false` | Enable verbose logging |

### Output Format

Each ad is saved as a separate dataset item with the following structure:

```json
{
  "ad_id": "1234567890",
  "status": "ACTIVE",
  "page_name": "Nike",
  "page_id": "123456789",
  "start_date": "2025-11-28",
  "end_date": "2025-11-28",
  "creative": {
    "body": "Ad text content...",
    "cta_type": "SHOP_NOW",
    "cta_text": "Shop now",
    "link_url": "https://example.com",
    "images": ["https://..."],
    "videos": ["https://..."],
    "cards": []
  },
  "targeting": {
    "reach_estimate": null,
    "info": null
  },
  "currency": "USD",
  "spend": null,
  "impressions": {
    "impressions_text": "10K-50K",
    "impressions_index": 3
  },
  "publisher_platforms": ["FACEBOOK", "INSTAGRAM"]
}
```

### How It Works

1. **Token Extraction**: Uses Playwright to extract authentication tokens from Facebook
2. **GraphQL API**: Makes direct GraphQL requests for fast, efficient data retrieval
3. **Smart Fallback**: If keyword search fails, queries the Typeahead API for related pages
4. **Duplicate Prevention**: Tracks `ad_id` to ensure each ad is only saved once
5. **Real-time Saving**: Pushes ads to the dataset immediately as they're found

### Use Cases

- **Competitive Analysis**: Monitor competitors' ad strategies
- **Market Research**: Discover trending ad creatives in your industry
- **Ad Inspiration**: Find successful ad formats and messaging
- **Brand Monitoring**: Track how brands are advertising across different countries
- **Academic Research**: Study advertising patterns and trends

### Limitations

- Requires Apify residential proxies for reliable operation
- Rate limited by Facebook's API
- Some ad fields may be `null` depending on ad type and status
- Timeframe limited to ads currently in Facebook Ad Library

### Performance

- Typically scrapes **30-50 ads per minute**
- Handles up to **5000 ads per search term**
- Supports multiple search terms in a single run
- Automatic retry with fallback search if initial query fails

### Author

Built with ❤️ for the Apify community

### Version

Current version: **0.1.12**

### License

Apache-2.0

# Actor input Schema

## `searchTerms` (type: `array`):

Keywords, Page Names, or Facebook URLs (e.g., 'Nike', 'https://www.facebook.com/UnderArmour'). Behavior depends on Search Mode.

## `searchMode` (type: `string`):

How to search for ads: 'keyword' (standard search), 'first\_suggestion' (use first typeahead suggestion), or 'facebook\_url' (extract page ID from FB URL or use direct page ID).

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

Select the country to scrape ads from.

## `adActiveStatus` (type: `string`):

Filter by ad status.

## `maxAds` (type: `integer`):

Maximum number of ads to scrape per search term (1-5000).

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

Proxy settings (Residential Proxy recommended).

## `enableSimilarSearch` (type: `boolean`):

When no ads found for keyword, search similar pages and their ads.

## `maxSimilarPages` (type: `integer`):

How many similar pages to search (only if 'Enable Similar Search' is active).

## `debugMode` (type: `boolean`):

Enable verbose logging.

## Actor input object example

```json
{
  "searchTerms": [
    "Nike"
  ],
  "searchMode": "keyword",
  "countryCode": "ALL",
  "adActiveStatus": "ALL",
  "maxAds": 100,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  },
  "enableSimilarSearch": true,
  "maxSimilarPages": 1,
  "debugMode": false
}
```

# Actor output Schema

## `overview` (type: `string`):

No description

## `dataset` (type: `string`):

No description

# 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 = {
    "searchTerms": [
        "Nike"
    ],
    "maxAds": 100
};

// Run the Actor and wait for it to finish
const run = await client.actor("kalirobot/fb-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 = {
    "searchTerms": ["Nike"],
    "maxAds": 100,
}

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

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

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

```

## CLI example

```bash
echo '{
  "searchTerms": [
    "Nike"
  ],
  "maxAds": 100
}' |
apify call kalirobot/fb-ad-library-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=kalirobot/fb-ad-library-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

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