# Meta Ad Library Scraper (`datapilot/meta-ad-library-scraper`) Actor

capturing ad IDs, page names, ad copy, image and video URLs, and CTA links. Uses with GraphQL network interception, deduplication, scrolling, and Apify Residential Proxy.

- **URL**: https://apify.com/datapilot/meta-ad-library-scraper.md
- **Developed by:** [Data Pilot](https://apify.com/datapilot) (community)
- **Categories:** Other
- **Stats:** 1 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 scraped results

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#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

📢 **Meta Ad Library** Scraper is a powerful Apify Actor designed to discover, track, and collect live advertising creative data directly from the **Meta Ad Library** using a real headless browser and GraphQL network interception. This tool provides comprehensive **Meta Ad Library** intelligence including ad copy text, page name, image creative, video creative, and call-to-action link for any keyword or country. Whether you're building a competitor ad monitoring tool, tracking creative trends, or conducting market research, the Meta Ad Library Scraper delivers actionable **Meta Ad Library** insights efficiently.

With direct GraphQL network interception, recursive JSON parsing, scroll-triggered pagination, and reliable Apify Dataset delivery, the Meta Ad Library Scraper ensures comprehensive **Meta Ad Library** coverage across any search keyword. It focuses on key **Meta Ad Library** signals including ad text, creative assets, and advertiser page name, making it an essential tool for competitive advertising research and creative intelligence.

***

### 📋 Table of Contents

- [Features](#-features)
- [Data Source](#-data-source)
- [How It Works](#-how-it-works)
- [Input](#-input)
- [Output](#-output)
- [Technical Stack](#-technical-stack)
- [Data Fields](#-data-fields-explained)
- [Use Cases](#-use-cases)
- [Quick Start](#-quick-start)
- [Configuration](#-configuration)
- [Performance](#-performance)
- [Important Notes](#-important-notes)
- [License & Legal](#-license--legal)

***

### 🔥 Features

- **Real Browser Rendering** – Uses Playwright (Chromium) to load the **Meta Ad Library** search page exactly as a real visitor would see it.
- **GraphQL Network Interception** – Listens for and captures Meta's internal GraphQL responses as they stream in, rather than scraping rendered HTML.
- **Recursive JSON Parsing** – Deeply searches every intercepted GraphQL payload for ad snapshot objects, regardless of nesting depth.
- **Keyword & Country Targeting** – Searches the **Meta Ad Library** for any keyword within a specific country's active ad set.
- **Automation Detection Evasion** – Masks the `navigator.webdriver` flag to reduce the chance of bot detection.
- **Scroll-Triggered Pagination** – Automatically scrolls the page to trigger additional backend GraphQL requests and capture more ads.
- **Multi-Asset Extraction** – Pulls ad copy text, image URL, video URL, and CTA link from each captured **Meta Ad Library** record.
- **Deduplication** – Removes duplicate ad records by ad ID or ad text before saving.
- **Residential Proxy Support** – Apify residential proxy for reliable **Meta Ad Library** access.
- **Configurable Item Cap** – Stop collecting once a set number of clean **Meta Ad Library** creatives has been reached.
- **Real-Time Dataset Push** – Pushes all collected **Meta Ad Library** records to Apify Dataset in a single batch.
- **Graceful Error Handling** – Continues the run even if individual network responses fail to parse.

***

### 📊 Data Source

#### **Meta (Facebook) Ad Library**

- **Authority**: Meta's own public-facing Ad Library (`facebook.com/ads/library`) and its internal GraphQL API
- **Access Method**: Headless Chromium via Playwright, with network response interception on GraphQL endpoints
- **Coverage**: Any active, publicly listed ad in the **Meta Ad Library** matching the given keyword and country
- **Data**: Raw GraphQL ad snapshot objects captured directly from the network stream
- **Access**: Public Ad Library interface, no API key required
- **Update Frequency**: Reflects each **Meta Ad Library** ad's current live/active state at time of run

***

### ⚙️ How It Works

The Meta Ad Library Scraper launches a real headless browser and navigates to the Ad Library search results for a given keyword and country. As the page loads, it attaches a network response listener that watches for Meta's internal GraphQL endpoints and captures any response containing ad snapshot data. The Actor then scrolls the page repeatedly to trigger additional backend GraphQL calls, capturing more ads with each scroll. Every intercepted payload is recursively searched for ad archive objects, from which ad text, page name, image URL, video URL, and CTA link are extracted. Captured ads are deduplicated by ad ID (or a text fingerprint when no ID is present) before being pushed to the Apify Dataset.

**Key Processing Steps:**

1. **Input Parsing** – Accept a search keyword, country code, max item count, and proxy setting
2. **Proxy Setup** – Configure Apify residential proxy for the browser session
3. **Browser Launch** – Start a headless Chromium instance with automation-detection evasion
4. **Network Listener Setup** – Attach a response handler that watches for **Meta Ad Library** GraphQL traffic
5. **Page Navigation** – Load the Ad Library search URL for the given keyword and country
6. **Scroll Loop** – Repeatedly scroll the page to trigger additional GraphQL requests
7. **GraphQL Interception** – Capture and buffer every relevant network response as it streams in
8. **Recursive Extraction** – Parse each captured payload for ad snapshot objects at any nesting depth
9. **Asset Parsing** – Extract ad text, image URL, video URL, and CTA link from each ad object
10. **Deduplication** – Filter out duplicate ads by ID or text fingerprint
11. **Item Cap Enforcement** – Stop collecting once the configured maximum item count is reached
12. **Dataset Push** – Push all collected records from the run in a single batch

**Key Benefits:**

- Pull **Meta Ad Library** creative data for any keyword without manually browsing the library
- Capture raw ad data straight from the network layer instead of fragile HTML scraping
- Monitor competitor and industry advertising activity over time
- Feed creative research pipelines, swipe files, or competitive intelligence dashboards
- Automate recurring **Meta Ad Library** checks as new ad creatives go live

***

### 📥 Input

The Actor accepts the following input parameters:

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `searchKeyword` | string | `"shopify"` | Keyword to search for within the **Meta Ad Library**. |
| `countryCode` | string | `"US"` | Two-letter country code to filter active ads by. |
| `maxItems` | integer | `30` | Maximum number of clean **Meta Ad Library** ad creatives to collect. |
| `useApifyProxy` | boolean | `true` | Enable Apify residential proxies. |

**Example Input:**

```json
{
  "searchKeyword": "fitness apparel",
  "countryCode": "US",
  "maxItems": 30,
  "useApifyProxy": true
}
```

**Scrape Ads for a Single Keyword:**

```json
{
  "searchKeyword": "shopify"
}
```

**Target a Different Country:**

```json
{
  "searchKeyword": "online courses",
  "countryCode": "GB",
  "maxItems": 50
}
```

***

### 📤 Output

The Actor pushes **Meta Ad Library** records with the following structure:

| Field | Type | Description |
|-------|------|-------------|
| `ad_id` | string | The unique ad archive ID from the **Meta Ad Library** |
| `page_name` | string | Name of the Facebook Page running the ad |
| `ad_text` | string | Primary ad copy/body text |
| `image_url` | string | URL of the ad's image creative, if present |
| `video_url` | string | URL of the ad's video creative, if present |
| `cta_url` | string | Destination link behind the ad's call-to-action |

**Example Meta Ad Library Record:**

```json
{
  "ad_id": "1234567890123456",
  "page_name": "Example Fitness Co.",
  "ad_text": "Get 20% off your first order — shop the new summer collection today.",
  "image_url": "https://scontent.xx.fbcdn.net/...",
  "video_url": "N/A",
  "cta_url": "https://examplefitness.com/shop"
}
```

***

### 🧰 Technical Stack

- **Browser Automation:** `playwright` (Chromium) for real, rendered access to the **Meta Ad Library**
- **Network Interception:** Playwright response listeners for capturing GraphQL traffic directly
- **JSON Parsing:** `json` with a recursive search algorithm for deeply nested ad objects
- **URL Handling:** `urllib.parse` for building the Ad Library search URL and parsing proxy URLs
- **Async:** `asyncio` for non-blocking browser interaction and scrolling
- **Proxy:** Apify Proxy with `RESIDENTIAL` configuration, wired into Playwright's launch options
- **Logging:** Apify Actor logging system
- **Platform:** Apify Actor serverless environment

***

### 📊 Data Fields Explained

#### **Ad Identity**

- **ad\_id**: The unique archive identifier assigned by the **Meta Ad Library**
- **page\_name**: The advertiser's Facebook Page name

#### **Creative Content**

- **ad\_text**: The primary text/copy shown in the ad
- **image\_url**: Direct link to the ad's image creative
- **video\_url**: Direct link to the ad's video creative (HD preferred, SD fallback)

#### **Conversion**

- **cta\_url**: The landing page URL behind the ad's call-to-action button

***

### 🎯 Use Cases

- **Competitor Ad Monitoring** – Track what ad creatives competitors are actively running
- **Creative Research** – Build swipe files of high-performing ad copy and creative formats
- **Trend Analysis** – Study messaging and creative trends across an industry or niche
- **Market Entry Research** – See what advertisers are already active in a target country
- **Agency Reporting** – Feed client competitive landscape reports with real ad data
- **Academic Research** – Study public advertising trends at scale
- **Compliance Monitoring** – Track how brands are positioning claims in live ad copy

***

### 🚀 Quick Start

#### **1. Prepare Input**

Go to Apify Console and enter:

```json
{
  "searchKeyword": "shopify",
  "countryCode": "US"
}
```

#### **2. Run the Actor**

Click **Start**. The Actor will:

- Launch a headless browser and open the **Meta Ad Library** search results
- Intercept GraphQL network traffic as the page loads and scrolls
- Extract and deduplicate ad creatives from the captured data
- Push all results to the Dataset

#### **3. Monitor Progress**

Console shows:

```
[Meta Ad Scraper] Starting GraphQL Interceptor for keyword: 'shopify' (US)
Intercepted 12 raw ad record(s) from GraphQL stream!
Done! Successfully saved 30 clean ad creative(s) to dataset.
```

#### **4. View & Download Results**

- **Results Tab**: All **Meta Ad Library** records
- **Export**: JSON, CSV, Excel, or HTML
- **Filter**: By page name or ad ID
- **API Access**: Available via the Apify API

***

### ⚙️ Configuration

Single keyword search:

```json
{
  "searchKeyword": "shopify"
}
```

Country-targeted search with item cap:

```json
{
  "searchKeyword": "fashion",
  "countryCode": "CA",
  "maxItems": 100
}
```

Run without proxy:

```json
{
  "searchKeyword": "shopify",
  "useApifyProxy": false
}
```

***

### 📈 Performance

#### **Processing Speed**

- One browser session per run, with 8 scroll cycles to trigger additional GraphQL requests
- \~2 seconds pause between each scroll to allow network requests to complete
- Slower than raw HTTP scraping since a full browser is launched, but necessary to trigger Meta's client-rendered GraphQL calls

#### **Resource Usage**

- Memory: Moderate to high, since a Chromium browser instance is launched and network traffic is buffered
- Network: Multiple GraphQL responses intercepted per scroll cycle
- Proxy: One residential proxy tunnel shared across the browser context for the run

***

### ⚠️ Important Notes

#### **Legal & Compliance**

- **Fair Use**: Respects the **Meta Ad Library**'s public interface and applies scroll pacing to avoid overloading requests
- **Public Data Only**: Retrieves only publicly visible ad data exposed through the Ad Library's own network traffic
- **Privacy**: Collecting ad data may be subject to privacy regulations and Meta's Terms of Service — use only for legitimate purposes
- **Legal**: Not legal advice — consult qualified professionals before using this data for compliance-sensitive decisions

#### **Data Quality**

- **Freshness**: Reflects each **Meta Ad Library** ad's active state at time of run
- **Completeness**: Image, video, or CTA fields may return `"N/A"` if a given ad doesn't use that asset type
- **Accuracy**: Sourced directly from Meta's own GraphQL network responses
- **Verification**: Cross-check high-stakes creative details against the live Ad Library website

#### **Best Practices**

- Always configure a residential proxy for the most reliable **Meta Ad Library** access
- Use broader keywords (e.g., "fashion", "shop") if a narrow keyword returns no ads
- Re-run periodically to catch newly launched ad creatives
- Expect some fields to occasionally return `"N/A"` if that asset type isn't present on the ad
- Adjust `maxItems` based on how many scroll cycles are needed for a given keyword's ad volume

***

### 📄 License & Legal

**Terms of Use:**

- Use for legitimate research, marketing, and competitive analytics purposes
- Respect Meta's Terms of Service
- Do not use for unsolicited contact, harassment, or unlawful surveillance
- Use **Meta Ad Library** data responsibly and in compliance with applicable privacy laws

**Disclaimer:**
Meta Ad Library Scraper is provided as-is for research and analytics purposes. Users are responsible for compliance with Meta's ToS and all applicable laws. This is not legal advice.

***

### ⚖️ Meta Ad Library Excellence

This Actor is optimized for **Meta Ad Library** research with:

- ✅ Real, browser-rendered GraphQL network interception
- ✅ Recursive parsing for maximum ad-object coverage
- ✅ Automation-detection evasion for more reliable access
- ✅ Deduplicated, clean creative output
- ✅ Real-time Dataset push
- ✅ Production-ready code

# Actor input Schema

## `searchKeyword` (type: `string`):

Enter brand name, keyword, or page name to search ads

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

2-letter ISO country code (e.g., US, BD, ALL)

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

Maximum number of ad creatives to extract

## `useApifyProxy` (type: `boolean`):

Enable Apify Residential Proxy to avoid anti-bot blocks

## Actor input object example

```json
{
  "searchKeyword": "shopify",
  "countryCode": "US",
  "maxItems": 30,
  "useApifyProxy": true
}
```

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("datapilot/meta-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 = {}

# Run the Actor and wait for it to finish
run = client.actor("datapilot/meta-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 '{}' |
apify call datapilot/meta-ad-library-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,datapilot/meta-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/JvnCrybtIrswgKaYK/builds/esqoGrOrBjBdBuSNI/openapi.json
