# Facebook Ads Library Scraper (`taupe_thrush/fb-ads-library-scraper-actor`) Actor

This Apify Actor scrapes ads from Facebook's Ad Library based on the provided URL. It will extract ad data, including ad content, page information, and targeting details. It automates the browsing process, handles dynamic content loading, and provides structured data output.

- **URL**: https://apify.com/taupe_thrush/fb-ads-library-scraper-actor.md
- **Developed by:** [MT](https://apify.com/taupe_thrush) (community)
- **Categories:** Social media, Automation, E-commerce
- **Stats:** 246 total users, 3 monthly users, 100.0% runs succeeded, 6 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $4.00 / 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.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

This Apify Actor scrapes ads from Facebook's Ad Library based on provided URL. It will extract comprehensive ad data including ad content, page information, and targeting details. It automates the browsing process, handles dynamic content loading, and provides structured data output.

### Features

- **Complete Ad Extraction**: Extracts all ads from Facebook Ad Library pages, not just the first few
- **Dynamic Content Loading**: Automatically scrolls and loads additional ads through GraphQL responses
- **Deduplication**: Prevents duplicate ads using persistent storage across runs
- **Comprehensive Data**: Extracts ad content, page details, timestamps, and targeting information
- **Flexible Input**: Configure the scraper using Facebook Ad Library URLs or page URLs
- **Structured Output**: Provides results in clean, machine-readable JSON format

### Input Schema

The actor is configured using a JSON object with the following properties.

#### URLs (Required)

You must provide Facebook Ad Library URLs or Facebook page URLs to scrape.

```json
{
  "startUrls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=ALL&view_all_page_id=123456789",
      "method": "GET"
    },
    {
      "url": "https://www.facebook.com/examplepage/",
      "method": "GET"
    }
  ]
}
```

#### Input Parameters

```json
{
  "startUrls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=ALL&view_all_page_id=123456789",
      "method": "GET"
    }
  ],
  "maxScrolls": 10,
  "waitTime": 5000
}
```

##### Input Fields

- `startUrls` (array, required): List of Facebook Ad Library URLs or Facebook page URLs to scrape
- `maxScrolls` (integer, optional): Maximum number of scroll attempts to load more ads (default: unlimited)
- `waitTime` (integer, optional): Wait time in milliseconds between actions (default: 5000)

#### Supported URL Types

1. **Facebook Ad Library URLs**: Direct links from Facebook's Ad Library with search parameters
   - Example: `https://www.facebook.com/ads/library/?active_status=all&ad_type=all&country=ALL&view_all_page_id=123456789`

2. **Facebook Page URLs**: Direct Facebook page URLs that will be converted to Ad Library searches
   - Example: `https://www.facebook.com/examplepage/`

### Output

The actor returns a dataset where each item represents a scraped Facebook ad.

#### Example Ad Output Item

```json
{
  "ad_archive_id": "123456789012345",
  "page_id": "987654321098765",
  "snapshot": {
    "body": {
      "text": "Discover our latest collection! Limited time offer."
    },
    "caption": "shop.example.com",
    "ctaText": "Shop Now",
    "ctaType": "SHOP_NOW",
    "linkUrl": "https://shop.example.com/collection",
    "title": "Summer Collection 2024",
    "images": [
      "https://scontent.example.com/image1.jpg"
    ],
    "videos": [],
    "pageId": "987654321098765",
    "pageName": "Example Store"
  }
}
```

#### Output Fields

The actor extracts the following fields for each ad:

- **Ad Identification**: `ad_archive_id`, `page_id`
- **Ad Content**: `snapshot.body.text`, `snapshot.title`, `snapshot.caption`
- **Call-to-Action**: `snapshot.ctaText`, `snapshot.ctaType`, `snapshot.linkUrl`
- **Media**: `snapshot.images`, `snapshot.videos`
- **Page Information**: `snapshot.pageId`, `snapshot.pageName`

### How It Works

1. **Page Loading**: The scraper loads Facebook Ad Library pages or converts page URLs to Ad Library searches
2. **Initial Extraction**: Extracts ads from initial page scripts containing `ad_library_main` data
3. **Dynamic Loading**: Scrolls through the page to trigger GraphQL requests for additional ads
4. **Deduplication**: Uses persistent storage to prevent duplicate ads across runs
5. **Data Processing**: Processes each ad's collated results and snapshot data
6. **Output**: Saves each unique ad as a separate item in the dataset

### Why Scrape Facebook Ads?

💪 **Competition Intelligence**: Analyze competitor advertising strategies and messaging

🕵️ **Market Research**: Understand industry trends and advertising patterns

📈 **Brand Monitoring**: Track how brands present themselves across different campaigns

🤳 **Creative Analysis**: Study ad creative elements and copywriting approaches

📊 **Performance Insights**: Gather data for advertising strategy optimization

### Usage

1. Navigate to the Actor page on the Apify platform
2. Click "Try actor"
3. Enter your input configuration in the JSON editor with Facebook Ad Library URLs or page URLs
4. Configure optional parameters like `maxScrolls` and `waitTime` if needed
5. Click "Start" to run the actor
6. Once the run is complete, view and download the results from the "Dataset" tab

### Technical Notes

- The scraper handles dynamic content loading through GraphQL responses
- Deduplication is implemented using persistent KeyValue storage
- Each ad is saved as a separate dataset item for easier analysis
- The scraper respects Facebook's rate limits and includes appropriate delays
- Supports both initial page script extraction and dynamic content loading

### Legal and Ethical Considerations

This scraper only extracts publicly available advertising data from Facebook's Ad Library. It does not:

- Extract private user information
- Bypass Facebook's intended public access mechanisms
- Violate Facebook's terms of service for public ad data

The Facebook Ad Library is designed for transparency and public access to advertising content. However, you should:

- Respect rate limits and avoid overwhelming Facebook's servers
- Use the data responsibly and in compliance with applicable laws
- Consider Facebook's Terms of Service and robots.txt guidelines

### Limitations

- The scraper may not capture ads that are heavily restricted by geographic or demographic targeting
- Some ads may have limited visibility based on Facebook's algorithmic decisions
- Performance may vary based on page size and ad volume
- Dynamic content loading depends on Facebook's current implementation

# Actor input Schema

## `startUrls` (type: `array`):

Meta Ads Library URLs to start with.

## `resultsLimit` (type: `integer`):

If you leave this field empty, you will get as many results as possible.

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

Select active status for ads.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&is_targeted_country=false&media_type=all&search_type=page&view_all_page_id=65604112975"
    }
  ]
}
```

# Actor output Schema

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

Collection of Facebook ads with their metadata, creative content, and targeting information

# 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 = {
    "startUrls": [
        {
            "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&is_targeted_country=false&media_type=all&search_type=page&view_all_page_id=65604112975"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("taupe_thrush/fb-ads-library-scraper-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 = { "startUrls": [{ "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&is_targeted_country=false&media_type=all&search_type=page&view_all_page_id=65604112975" }] }

# Run the Actor and wait for it to finish
run = client.actor("taupe_thrush/fb-ads-library-scraper-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 '{
  "startUrls": [
    {
      "url": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=ALL&is_targeted_country=false&media_type=all&search_type=page&view_all_page_id=65604112975"
    }
  ]
}' |
apify call taupe_thrush/fb-ads-library-scraper-actor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,taupe_thrush/fb-ads-library-scraper-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/b4a4rc3audvZEecUc/builds/qYc5BnygyfXA71Poq/openapi.json
