# Facebook Ads Library Scraper (`chenglianglin/fb-ad-library-actor`) Actor

Scrape ads from Meta's public Facebook Ads Library by keyword or Page ID.

- **URL**: https://apify.com/chenglianglin/fb-ad-library-actor.md
- **Developed by:** [Chengliang Lin](https://apify.com/chenglianglin) (community)
- **Categories:** E-commerce, Automation, Integrations
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.73 / 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 Ads Library Scraper

Scrape ads from Meta's public [Ads Library](https://www.facebook.com/ads/library/) by keyword or advertiser Page ID.

The Actor opens the Ads Library in a browser, intercepts GraphQL responses, and writes one Dataset row per ad plus a single `ads-by-page.json` file in the default **Key-Value Store**.

This is not the official Graph API `ads_archive` endpoint. That API only returns political / issue ads in most regions. This Actor uses the public library page, so it can collect commercial ads.

[繁體中文](README.zh-Hant.md) · [日本語](README.ja.md)

### Input

Provide **either** `query` **or** `pageId`. If both are set, `pageId` wins and `query` is ignored.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `query` | String | Yes, unless `pageId` is set | — | Keyword to search in the Ads Library. |
| `pageId` | String | Yes, unless `query` is set | — | Numeric Facebook Page ID. Lists that advertiser's ads. |
| `country` | String | No | `TW` | ISO country code, or `ALL`. Allowed: `ALL`, `TW`, `US`, `GB`, `JP`, `KR`, `SG`, `HK`, `AU`, `CA`, `DE`, `FR`. |
| `category` | String | No | `all` | Ad category. `all`, `political_and_issue_ads`, `housing_ads`, `employment_ads`, `credit_ads`. |
| `mediaType` | String | No | `all` | Creative type. `all`, `image`, `meme`, `image_and_meme`, `video`, `none`. |
| `sortBy` | String | No | `mostRecent` | Result order. `mostRecent` or `impressions`. |
| `activeStatus` | String | No | `active` | `active`, `inactive`, or `all`. Use `all` when searching historical ads. |
| `minDate` | String | No | — | Only ads that **started running** on or after this date (`YYYY-MM-DD`). |
| `maxDate` | String | No | — | Only ads that **started running** on or before this date (`YYYY-MM-DD`). |
| `maxItems` | Integer | No | `20` | Maximum number of ads to collect (`1`–`500`). |
| `maxScrollRounds` | Integer | No | scales with `maxItems` | How many times to scroll for more results (`1`–`80`). Leave empty to scale automatically. |
| `proxy` | Proxy | No | Residential | Apify Proxy. Use **Residential**; datacenter IPs typically get HTTP 403 from Meta. |

#### Example input

```json
{
    "query": "skincare",
    "country": "TW",
    "category": "all",
    "mediaType": "all",
    "sortBy": "mostRecent",
    "activeStatus": "active",
    "minDate": "2026-01-01",
    "maxDate": "2026-06-30",
    "maxItems": 20
}
```

`minDate` / `maxDate` match the Ads Library date picker (**start-running date**), not “was delivering during this window”.

### Output

Each ad is written to the default **Dataset** (one row per ad, shown as a table in Console). The same ads are grouped by advertiser in one Key-Value Store file.

| Storage | Key / item | Description |
| --- | --- | --- |
| Dataset | one item per ad | Table view in Console. Use this for CSV / Excel export. |
| Key-Value Store | `ads-by-page.json` | Object keyed by `page_id` (or `unknown-{ad_archive_id}`), each value an array of ads. |
| Key-Value Store | `OUTPUT` | Run summary: `adCount`, `pageCount`, `files`. |

#### `OUTPUT` record

| Field | Type | Description |
| --- | --- | --- |
| `adCount` | Integer | Number of ads saved. |
| `pageCount` | Integer | Number of advertiser keys in `ads-by-page.json`. |
| `files` | String\[] | List of Key-Value Store keys that were written. |

#### Ad object

Each ad in the Dataset and in `ads-by-page.json` has these fields:

| Field | Type | Description |
| --- | --- | --- |
| `ad_archive_id` | String | Ads Library archive ID. |
| `page_id` | String | null | Advertiser Facebook Page ID. |
| `page_name` | String | null | Advertiser page name. |
| `is_active` | Boolean | null | Whether the ad is currently running. |
| `start_date` | Number | null | Unix timestamp (seconds) when the ad started running. |
| `end_date` | Number | null | Unix timestamp (seconds) when the ad stopped, if ended. |
| `publisher_platform` | String\[] | Platforms such as `FACEBOOK`, `INSTAGRAM`. |
| `body_text` | String | Primary ad copy. |
| `title` | String | null | Headline / title. |
| `cta_text` | String | null | Call-to-action label, e.g. `Shop now`. |
| `link_url` | String | null | Destination URL. |
| `image_urls` | String\[] | Image URLs from single/multi-image ads and carousel cards. |
| `video_urls` | String\[] | Video URLs (HD when available, otherwise SD). |
| `library_url` | String | Direct Ads Library URL for this ad. |
| `snapshot` | Object | null | Creative payload: images, videos, carousel `cards`, CTA, page profile. |
| `raw` | Object | Original GraphQL ad object. |

`snapshot.display_format` is typically `IMAGE`, `VIDEO`, `CAROUSEL`, or `MULTI_IMAGES`. Carousel slides live in `snapshot.cards` (title, CTA, link, image/video per card).

Media is stored as Facebook CDN URLs, not downloaded files.

#### Example `OUTPUT`

```json
{
    "adCount": 5,
    "pageCount": 5,
    "files": [
        "ads-by-page.json"
    ]
}
```

#### Example `ads-by-page.json`

```json
{
    "111111111111111": [
        {
            "ad_archive_id": "755606263512566",
            "page_id": "111111111111111",
            "page_name": "Example Brand",
            "is_active": true,
            "start_date": 1735689600,
            "end_date": null,
            "publisher_platform": ["FACEBOOK", "INSTAGRAM"],
            "body_text": "Ad copy…",
            "title": "Headline",
            "cta_text": "Shop now",
            "link_url": "https://example.com/product",
            "image_urls": ["https://scontent.xx.fbcdn.net/…"],
            "video_urls": ["https://video.xx.fbcdn.net/…"],
            "library_url": "https://www.facebook.com/ads/library/?id=755606263512566&country=TW",
            "snapshot": {},
            "raw": {}
        }
    ]
}
```

### Notes

- Enable **Apify Proxy → Residential**. Datacenter IPs are usually blocked by Meta with HTTP 403.
- The browser does not download ad images, videos, fonts, or Facebook telemetry beacons. Creative URLs are still saved in the output.
- The library is infinite-scroll. The Actor scrolls until it reaches `maxItems`, 6 empty rounds, or `maxScrollRounds`.
- Meta may show cookie consent or a login wall. Overlays are dismissed when possible, but not guaranteed.
- Follow the [Ads Library terms](https://www.facebook.com/ads/library) and local law. Use this only for public transparency data and competitive research.

# Actor input Schema

## `query` (type: `string`):

Keyword to search in the Ads Library. Required unless pageId is set.

## `pageId` (type: `string`):

Numeric Facebook Page ID. When set, lists that advertiser's ads and ignores query.

## `country` (type: `string`):

ISO country code to filter ads, or ALL.

## `category` (type: `string`):

Ad category shown in the Ads Library.

## `mediaType` (type: `string`):

Filter by creative media type.

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

Result order in the Ads Library.

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

Whether to include currently running ads.

## `minDate` (type: `string`):

Only ads that started running on or after this date (YYYY-MM-DD). Matches the Ads Library date picker.

## `maxDate` (type: `string`):

Only ads that started running on or before this date (YYYY-MM-DD). Matches the Ads Library date picker.

## `maxItems` (type: `integer`):

Maximum number of ads to collect.

## `maxScrollRounds` (type: `integer`):

How many times to scroll the library page while waiting for more GraphQL results. Leave empty to scale with maxItems.

## `proxy` (type: `object`):

Meta blocks most datacenter IPs with HTTP 403. Use Apify Proxy → Residential.

## Actor input object example

```json
{
  "query": "skincare",
  "country": "TW",
  "category": "all",
  "mediaType": "all",
  "sortBy": "mostRecent",
  "activeStatus": "active",
  "maxItems": 20,
  "maxScrollRounds": 20,
  "proxy": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}
```

# Actor output Schema

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

One dataset item per ad.

## `adsByPage` (type: `string`):

Single key-value store record ads-by-page.json.

## `summary` (type: `string`):

OUTPUT record with adCount, pageCount, and files.

# 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 = {
    "query": "skincare",
    "proxy": {
        "useApifyProxy": true,
        "apifyProxyGroups": [
            "RESIDENTIAL"
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("chenglianglin/fb-ad-library-actor").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 = {
    "query": "skincare",
    "proxy": {
        "useApifyProxy": True,
        "apifyProxyGroups": ["RESIDENTIAL"],
    },
}

# Run the Actor and wait for it to finish
run = client.actor("chenglianglin/fb-ad-library-actor").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 '{
  "query": "skincare",
  "proxy": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ]
  }
}' |
apify call chenglianglin/fb-ad-library-actor --silent --output-dataset

```

## MCP server setup

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

```

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/hScpkrZ9dvQVRQpaR/builds/1wcVabiNH4ri0e0uu/openapi.json
