# Meta Ads Library Scraper & Media Archive — Beta (`magenta_courser/meta-ads-library-scraper`) Actor

Search Meta ads by keyword or page ID. Get archived media, ad changes and Instagram followers. 10-day beta offer: no Actor fee; Apify usage applies.

- **URL**: https://apify.com/magenta_courser/meta-ads-library-scraper.md
- **Developed by:** [SUNGHWAN CHO](https://apify.com/magenta_courser) (community)
- **Categories:** Social media, Marketing
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

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

## 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

## Meta Ads Library Scraper

Enter a keyword, domain, or Facebook Page ID to get public Meta Ad Library ads with creative text, images, videos, carousel cards, stored media links, observed status changes, and available Instagram follower counts.

### 10-day beta test discount: pay only Apify usage

**November 25–December 4, 2026, inclusive (Asia/Seoul / KST). Actor fee: $0.** This launch beta uses **Pay per usage**: there is no developer fee per ad or per run. You pay Apify for the resources your runs use, including compute, residential proxy traffic, data transfer, and storage. This is an at-cost launch offer, not a claim that Apify infrastructure is free. Failed or partial runs can still incur usage costs. No former price or percentage discount is claimed.

Saved media is stored in your account's named storage. Links remain available while their records and account are retained; storage, later reads, and access can incur ongoing usage charges. Start with 1–3 ads and check the run's actual usage before increasing the limit. Pricing will be reviewed after the beta, and any future change will follow Apify's notice rules; there is no scheduled automatic price increase.

**Found an error? Please report it in a [review](https://apify.com/magenta_courser/meta-ads-library-scraper/reviews).** Include the run ID, the input filters with any sensitive information removed, and what you expected versus what happened. You can also use the [Issues tab](https://apify.com/magenta_courser/meta-ads-library-scraper/issues) for troubleshooting. Honest feedback, including failures, helps us improve the beta. Do not post API tokens or account cookies.

**한국어 — 10일 베타 테스트 할인가 (11월 25일~12월 4일, 한국시간)**\
액터 자체 이용료는 **$0**이며 Apify 실제 실행·주거용 프록시·전송·저장 사용료만 부담합니다. 오류가 발생하면 **리뷰로 제보해주세요.** 실행 ID, 민감한 정보를 지운 입력 조건, 예상한 결과와 실제 오류를 적어주시면 재현에 도움이 됩니다. 자세한 문의는 Issues에서도 가능합니다. 베타 이후 요금은 검증 결과와 사전 고지 규칙에 따라 안내합니다.

This is an early public beta. Small cloud runs have validated ad collection, media archiving, available Instagram followers, and repeated-ad history comparison. Multi-day reliability and successful session recovery after a live source rejection have not yet been demonstrated. Inspect each run's coverage and enrichment status before using it for monitoring.

The implementation reads Meta's logged-out public endpoints directly; it does not call another paid scraper or require a Facebook or Instagram login. Availability depends on the data Meta returns. This is an independent tool, not an official Meta product.

### Start a run

Provide exactly one of `keyword` or `pageId`. Keep page IDs as strings. Choose a country, an active-status filter, and a result limit.

Keyword search:

```json
{
  "keyword": "running shoes",
  "country": "US",
  "activeStatus": "all",
  "maxAds": 20
}
```

Domain search uses the same keyword input:

```json
{
  "keyword": "example.com",
  "country": "ALL",
  "activeStatus": "active",
  "maxAds": 20,
  "archiveMedia": true,
  "includeInstagramFollowers": true,
  "trackChanges": true
}
```

The domain is passed to Meta's keyword search. It is not a strict destination-domain filter, and results do not establish that every ad linking to that domain was found.

Page-ID search:

```json
{
  "pageId": "15087023444",
  "country": "ALL",
  "activeStatus": "all",
  "maxAds": 50,
  "historyNamespace": "competitor-watch"
}
```

Use the numeric `view_all_page_id` from a page's Ad Library URL. This version does not accept a Facebook page name, Instagram handle, or pasted URL in `pageId`.

### Input reference

| Input | Default | Meaning |
|---|---|---|
| `keyword` | — | A keyword or domain, up to 500 characters. Required unless `pageId` is supplied. |
| `pageId` | — | Numeric Facebook Page ID as a string, 1–30 digits. Required unless `keyword` is supplied. |
| `country` | `ALL` | `ALL` or a two-letter country code, such as `KR`, `US`, or `DE`. Lowercase is normalized to uppercase. |
| `mediaType` | `all` | Optional `all`, `image`, or `video` source filter. Filtered searches use separate history scopes. |
| `activeStatus` | `all` | `active`, `inactive`, or `all`. Applies to the search. Previously observed active ads may be checked separately for changes. |
| `maxAds` | `50` | Maximum unique ads from the search, 1–1,000. Status-check observations may add rows beyond this limit. |
| `archiveMedia` | `true` | Download supported creative files to a named media store and add `media_assets`. |
| `includeInstagramFollowers` | `true` | Read available advertiser Instagram information from ad details. Details are cached per Facebook Page during a run. |
| `trackChanges` | `true` | Compare observations with this search's stored history. |
| `historyNamespace` | `default` | Separate monitoring histories for the same search. 1–64 letters, digits, hyphens, or underscores. |
| `maxStatusChecks` | `10` | Maximum previously active, currently missing ad IDs to look for in bounded page-specific searches, 0–100. Setting 0 disables these extra checks. |
| `maxFileSizeMb` | `20` | Maximum bytes accepted per media file in MiB, 1–50. A file larger than the remaining run budget is also rejected. |
| `maxTotalMediaMb` | `100` | Shared media-download budget in MiB, 1–1,000. Applies across all ads and counts received bytes from failed transfers too. |
| `pageSize` | `30` | Source result groups per page, 1–30. Multiple collated ads may share a group. Page size does not change the history scope. |
| `requestDelayMs` | `2000` | Minimum request start interval, 1,000–10,000ms, shared across replacement sessions. Recovery also applies a separate backoff. |
| `httpTransport` | `impit` | Maintained native HTTP client with browser-compatible TLS and HTTP behavior. `got` retains the earlier client for comparisons. Certificate verification is enabled for both. |
| `maxRecoveries` | `2` | Maximum recovery attempts, 0–2, across the entire run: at most 3 source attempts including the first. |
| `recoveryDelayMs` | `20000` | Initial recovery backoff, 10,000–60,000ms. With rejection recovery enabled, the second backoff doubles; a longer server Retry-After takes priority. |
| `recoverSourceRejections` | `true` | Allow bounded fresh HTTP sessions after plain HTTP 403, HTTP 429, or explicit GraphQL rate limits. Login, verification challenges, and redirects still stop. |
| `maxRequests` | `300` | HTTP request cap for the entire run, 2–3,000. Includes initialization, search, details, status checks, and media downloads. |
| `maxRunSeconds` | `240` | Time limit for starting new HTTP requests, 30–480 seconds. An in-flight request may finish after this time. |
| `proxyConfiguration` | US residential Apify proxy | Defaults to `{ "useApifyProxy": true, "apifyProxyGroups": ["RESIDENTIAL"], "apifyProxyCountry": "US" }`. Applies to Meta search and detail requests; the selected proxy must be available to the account. |

Media downloads are sequential and include available HD, SD, and preview versions; a video can therefore consume the budget more than once. Media CDN files are downloaded directly rather than through the residential proxy, reducing proxy bandwidth use. A failed direct download is reported in its manifest entry; there is no automatic paid-provider fallback. Start with a small `maxAds` when archiving videos. Request and media limits are controls on work performed, not a guaranteed dollar spending ceiling.

If an ISP-specific `*.fna.fbcdn.net` image/video host fails DNS lookup (`ENOTFOUND`) before receiving bytes, one direct request to Meta's corresponding public CDN host is allowed. The signed path and query remain intact. This does not retry HTTP access denials, certificate failures, rate limits, or exhausted budgets. The original `source_url` is preserved; `download_route` identifies `direct` or `public_cdn_dns_fallback`. Both requests consume the same run budget.

### Dataset output

Each row represents one unique observed ad. IDs are strings, numeric metrics are numbers, unavailable scalar values are `null`, and image/video/card collections are arrays. The Actor normalizes dates to UTC ISO 8601 strings.

| Group | Fields |
|---|---|
| Identification | `ad_archive_id`, `page_id`, `page_name`, `collation_id`, `collation_count`, `ad_library_url` |
| Status and dates | `is_active`, `start_date`, `end_date` |
| Placement | `publisher_platform` |
| Creative text | `body.text`, `title`, `link_description`, `cta_text`, `link_url`, `caption` |
| Snapshot | `snapshot.display_format`, the same creative-text fields, `snapshot.images`, `snapshot.videos`, `snapshot.cards` |
| Advertiser | `snapshot.page_like_count`, `page_categories`, `branded_content`; categories and branded content also appear inside `snapshot` |
| Instagram | `instagram_username`, `instagram_followers`, `instagram_followers_status`, `instagram_followers_source`, `instagram_followers_observed_at` |
| Archived files | `media_assets` |
| Monitoring | `change_type`, `is_new`, `turned_off`; with tracking enabled: `previous_is_active`, `first_seen_at`, `last_seen_at`, `previous_run_id` |
| Provenance | `schema_version`, `source`, `observed_at`, `observation_source` |

`collation_count` is Meta's grouping count, not the number of separately exported ads. The Actor preserves Meta's reported `end_date`; it does not infer inactive status from a date. Use the explicit `is_active` field.

#### Images, videos, and carousel cards

`snapshot.images[]` includes available `original_image_url`, `resized_image_url`, `watermarked_image_url`, and `watermarked_resized_image_url` fields.

`snapshot.videos[]` includes available `video_hd_url`, `video_sd_url`, `video_preview_image_url`, `watermarked_video_hd_url`, and `watermarked_video_sd_url` fields.

`snapshot.cards[]` retains each card's own `body.text`, `title`, `link_description`, `cta_text`, `link_url`, and `caption`, plus its image and video URL fields. Nested card `images[]` and `videos[]` are included when Meta provides them. Fields with no source value remain `null`; missing media collections become empty arrays. The source's text is preserved, including any unresolved dynamic-creative placeholders.

### Stored media links

With `archiveMedia: true`, the Actor downloads supported image and video files from Meta media CDN hosts and stores their bytes in the named cloud KV store `meta-ads-media-<actorId>`. It checks media content before saving and uses a content hash as the file key. Identical content shares the same storage key; repeated references can share one stored URL.

Original URLs remain in `snapshot`. Use `media_assets[].stored_url` for the stored copy. The manifest maps each file back to its exact location in the ad:

```json
{
  "field_path": "snapshot.videos[0].video_hd_url",
  "source_url": "https://video.example.fbcdn.net/source.mp4",
  "kind": "video",
  "stored_url": "https://api.apify.com/v2/key-value-stores/STORE_ID/records/media-CONTENT_HASH.mp4?signature=RECORD_SIGNATURE",
  "storage_key": "media-CONTENT_HASH.mp4",
  "status": "stored",
  "bytes": 1048576,
  "content_type": "video/mp4",
  "download_route": "direct",
  "error": null
}
```

This is a schematic example, not a live file. Every manifest entry has `field_path`, `source_url`, `kind`, `stored_url`, `storage_key`, `status`, `bytes`, `content_type`, `download_route`, and `error`. Failed or skipped downloads have a null route. Reused references can also have `reused: true`.

| Media status | Meaning |
|---|---|
| `stored` | File saved in cloud storage; `stored_url` is available. |
| `stored_local` | File saved during a local run; there is no public cloud URL. |
| `failed` | Download or storage failed, the file was too large, or the response was not supported media. Read `error`; `stored_url` is `null`. |
| `skipped` | The run's media budget was exhausted. No stored URL is claimed. |

Named stores do not expire automatically under Apify's ordinary retention policy. Record links have no scheduled expiry and remain usable while the record, storage, account, and access configuration are retained. Deleting the record or store removes the file. Storage and access charges continue after the scraping run finishes. This is persistent storage, not an unconditional promise that a URL will work forever. [Named-store retention](https://docs.apify.com/storage/key-value-store), [record-link access](https://docs.apify.com/account/collaboration/general-resource-access).

The Actor uses named storage permissions for the account running it; publishing the Actor does not make that account’s entire storage public. Share only the intended record URLs. No account API token is inserted into dataset media URLs. Setting `archiveMedia: false` returns `media_assets: []` and leaves the original, potentially expiring CDN URLs available.

### Instagram follower counts

The Actor reads the advertiser information returned by Meta's ad-details endpoint, using `advertiser.ad_library_page_info.page_info.ig_followers`. The count is associated with the advertiser's linked Instagram account; it is not the Facebook page-like count and is not inferred from the advertiser's name.

| `instagram_followers_status` | Meaning |
|---|---|
| `ok` | A numeric follower count was returned. The source path and observation time are included. |
| `unavailable` | Meta did not return a usable count or advertiser information. |
| `identity_mismatch` | The returned advertiser page ID did not match the requested page. No count is attached. |
| `failed` | The detail request failed. A sanitized `instagram_followers_error` code is included. |
| `not_requested` | The option was disabled or no page ID was available for the request. |

An unavailable count remains `null`, not zero. A real source value of zero remains zero. The Actor does not visit private profiles or request account credentials to fill missing values.

### New and deactivated ads

Keep the same search and `historyNamespace` across runs. History is separated by keyword or page ID, country, active-status filter, and namespace. Changing any of these starts a separate comparison history. `maxAds` is not part of the history key, so increasing a limit can reveal previously unobserved ads.

| `change_type` | Meaning | `is_new` | `turned_off` |
|---|---|---|---|
| `baseline` | First successful observation for this search. It establishes the baseline. | `null` | `null` |
| `new` | Ad ID was not in the retained history and is now observed. This does not prove that it was launched since the last run. | `true` | `false` |
| `first_seen` | ID is now observed, but older history was pruned, so historical novelty is unknown. | `null` | `false` |
| `deactivated` | Previous observation explicitly said active; current observation explicitly says inactive. | `false` | `true` |
| `reactivated` | Previous observation explicitly said inactive; current observation explicitly says active. | `false` | `false` |
| `unchanged` | The same explicit active/inactive state was observed again. | `false` | `false` |
| `status_unknown` | A previous or current active state is unavailable. | `false` | `null` |
| `not_requested` | `trackChanges` is disabled. | `null` | `null` |

An ad absent from the current search is not automatically marked inactive. The Actor attempts up to `maxStatusChecks` follow-up checks for previously active missing ad IDs, least-recently checked first. Failed and unavailable checks also advance their scheduling timestamp after a successful dataset/history commit, without changing the last observed ad state. Meta's ad-detail response used for Instagram enrichment does not provide the active state in the live response tested here. Status checks therefore search that advertiser's first page of inactive ads, then its first page of all ads if necessary, requesting 30 results per page. These page/status searches are cached during the run and shared by checks for the same advertiser and country.

A check creates a status observation only when the exact ad ID and page ID are found with an explicit boolean active state. It does not paginate these follow-up searches; an ad outside these bounded pages remains unknown. Confirmed rows use `observation_source: "previous_ad_status_check"`; normal search rows use `"search"`.

This means an `active` search may also return an explicitly confirmed inactive ad from a previous run. Search rows are capped by `maxAds`, while status-check rows are separately capped by `maxStatusChecks`. The maximum possible returned count is their sum. Failed or unavailable status lookups remain unresolved and do not manufacture deactivation events.

`RUN_SUMMARY.comparison.missing_ids` lists retained IDs not observed in the current run, with `missing_count` and `absence_means_inactive: false`. `status_checks` records attempted checks, and `status_checks_pending` reports previously active missing ads beyond the check limit. Missing IDs can reflect search limits, ranking changes, source failures, removed archives, or actual changes; the Actor does not choose a cause without evidence.

History is updated only after dataset rows are saved. Failed history reads, stale observations, and incomplete empty results do not replace an existing baseline. The store retains up to 10,000 ad observations per search; pruning is reported as `history_truncated`, and later unseen IDs use `first_seen` rather than a definite `new` label.

Cloud runs sharing the same history scope use a server-side lease. A competing run fails with `history_scope_busy` instead of racing the baseline update. Different search scopes can run independently. Local runs have no distributed lease and should be run serially for a shared history. A separate last-state check also prevents promotion when another writer has changed the baseline.

### Coverage and diagnostics

Each run writes `RUN_SUMMARY` to its default KV store. Inspect it alongside the dataset:

- `status`, `stop_reason`, `search_pages`, and `search_ads` describe search coverage.
- `returned_rows` includes search rows and any confirmed status-check observations.
- `source_errors` preserves source failures and field-level GraphQL errors.
- `comparison`, `history_saved`, and any `history_error` describe monitoring updates.
- `status_checks` and `status_checks_pending` describe bounded follow-up checks.
- `instagram` counts rows with available, unavailable, or failed enrichment.
- `media` reports references, saved/cached/failed/skipped items, and byte counts. Reference counts are not unique-file counts.
- `http`, `http_transport`, `http_sessions`, `document_ids`, `media_store_id`, and `history_store_id` support technical diagnosis. Session sequence numbers show proxy-session replacement, not proof of a different exit IP.

Search `complete` means the source's returned pagination was exhausted for that query. It does not certify that Meta indexed every ad. `bounded` means the configured result limit was reached. `partial` means usable ads were collected but the source or pagination left coverage incomplete. `failed` means the run could not complete its required work; inspect its error rather than treating an empty dataset as zero ads.

`enrichment_status` is separate from search coverage. It is `partial` when requested Instagram counts are unavailable or failed, or when media files fail or are skipped. Check the individual statuses to identify the affected ads and files. A request cap or time limit can leave enrichment incomplete after useful search rows were collected; a complete enrichment pass still cannot supply media fields absent from Meta's response.

### Operating limits

- Public data only; no account login or user session cookies are accepted. Server-issued anonymous device cookies stay in memory. Bootstrap and queries use one consistent HTTP session; recovery replaces the proxy session, cookies, headers, and bootstrap context together.
- No competing paid Actor or paid third-party data API is used as a supply source.
- Search results depend on Meta's indexing, country coverage, archive availability, and current public schema. Inactive/all searches cannot restore ads Meta no longer exposes.
- The Actor uses bounded serial requests. Rate limits, access denials, redirects, and unavailable schemas are reported as source errors; they are not converted into empty successful observations.
- Media download failures do not erase the original creative fields. Large files may require a higher file budget or a smaller search.
- Source CDN links and archived links have different lifetimes. Use only successful `stored_url` entries when durable media is required.
- The beta has no developer fee. Stored creative files, history, HTTP traffic, residential proxies, and compute are billed as Apify platform usage to the running account. Usage and post-run storage charges are separate from the $0 Actor fee.

For development, source collection, normalization, history comparison, media storage, and run orchestration are separate modules in `src/`. Tests are under `test/`; their pass status and cloud verification belong in the validation report rather than being assumed from the existence of the files.

### Initial validation observations

On 2026-11-24, the initial private cloud probe using an Apify datacenter proxy was rate-limited. The same build with a US residential proxy returned one ad and stored two image files, with an observed run cost of approximately $0.0031. This is a small-run observation, not a 1,000-ad cost measurement or a long-term availability guarantee. Two subsequent residential probes were rate-limited again; cloud reliability remains unverified. A transport fix now keeps one anonymous HTTP session per run. A separate local ad-detail request returned Depop's linked Instagram follower count as 939,067; follower availability for other advertisers remains source-dependent.

The direct-CDN media route and bounded page-search status-check route were added after that initial cloud sample. Consult the validation report for their subsequent build-specific results.

`comparison.new_ad_detection_complete` is true only when both the preceding and current searches are complete and history is unpruned. `history_retention_complete` reports retention alone; a bounded search is never an exhaustive new-ad monitor.

### Follow-up robustness changes

If repeated observations of the same ad conflict within one run, the Actor reports `status_conflict: true` and `is_active: null` with partial coverage. It never uses the first conflicting state to manufacture a deactivation. Multiple complete GraphQL response chunks are combined; unsupported incremental patches fail explicitly instead of dropping their ads. The cloud history lease is checked before dataset append and again before baseline promotion.

`RUN_SUMMARY.source_diagnostics` contains only HTTP status, GraphQL numeric error codes, request operation, cursor presence, and names of available context fields. It never contains page response bodies, cookie/token values, request variables, or cursor values. A source rate-limit response does not by itself identify an IP restriction as its cause.

#### Collection recovery (beta)

`sourceMode` is `http` (default, 256 MB), `browser` (use at least 1024 MB), or `auto` (HTTP with browser recovery; allocate at least 1024 MB). Browser mode uses a new logged-out Chrome context and reads public initial HTML/GraphQL results before making additional requests. No user browser profile or account cookies are used. The Playwright dependency is pinned to the cloud image version; local fixture tests do not require installing it into the shared node_modules.

HTTP collection defaults to pinned `impit` 0.14.9. It verifies TLS certificates and uses the library's native Chrome profile with distinct navigation and GraphQL POST headers. That library profile is not a claim of matching another vendor's browser version. `got-scraping` remains available as `httpTransport: "got"` for comparisons and for the bounded direct-CDN downloader.

Transient network failures and expired sessions can recover up to `maxRecoveries` (default 2, maximum 2). `recoverSourceRejections: true` also allows plain HTTP 403, HTTP 429, and GraphQL rate-limit responses to start a fresh HTTP session after backoff. A rejection replaces the proxy-session identifier, anonymous cookies, and bootstrap context together; the proxy provider can still reuse an exit IP. There are at most three source attempts for the entire run, including enrichment and status checks. The initial wait is `recoveryDelayMs` (default 20000), the next wait doubles, and a longer server Retry-After is honored. If the remaining deadline cannot accommodate a wait, the run stops.

Login requirements, redirects, CAPTCHA, and verification challenges always stop. HTTP rejection recovery stays on HTTP; it does not switch into a browser challenge flow. `auto` can switch to a browser for rendering/session/network failures only. Set `recoverSourceRejections: false` or `maxRecoveries: 0` to disable rejection recovery.

Search restarts with a fresh cursor and deduplicates replayed IDs. All attempts share request and time budgets. This recovery works within a running process; persistent cross-run partial checkpoints are not implemented. Transport and retry settings do not alter the monitoring history scope.

`httpBootstrapMode: "library"` enables an advanced comparison path that reads the actual public search page and its initial JSON. The previously validated `"home"` initialization remains the default until live comparison proves a better default. Browser mode always initializes the library page. `maxBrowserRequests` (default 160) separately limits page assets and background requests; images, fonts and media playback are blocked. Chromium byte observations add a best-effort 20 MiB transfer/rendering threshold; in-flight traffic can exceed a threshold before cancellation. Creative archiving uses the existing separately bounded CDN downloader.

`RUN_SUMMARY.source_diagnostics` now separates attempts and recovery events. It contains numeric statuses, field names and fixed error codes, without raw HTML, cookies, tokens, cursor values or request bodies. Browser transport counters and `session_restarts` describe what actually ran. A recovered request is not proof of long-term source availability.

# Actor input Schema

## `keyword` (type: `string`):

Search public ad text. Provide keyword OR pageId. A domain is sent as a search term, not an exact landing-domain filter.

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

Numeric Facebook page ID. Provide this OR keyword.

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

Two-letter country code (US, KR, GB, DE) or ALL. Meta only retains some inactive commercial ads in supported regions.

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

Search filter. Historical status checks may additionally report ads that have since stopped.

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

Maximum unique search results. Up to maxStatusChecks previous ads can be emitted additionally to confirm status changes.

## `archiveMedia` (type: `boolean`):

Download original/resized images, HD/SD videos, previews and card media to a named KV store. URLs do not expire while records/account are retained; ongoing storage charges apply.

## `includeInstagramFollowers` (type: `boolean`):

One public advertiser detail request per page. Missing or failed counts are null, never zero.

## `trackChanges` (type: `boolean`):

Maintain Actor-specific history. Same keyword/page/country/status/namespace uses the same baseline. Missing search rows never prove deactivation.

## `historyNamespace` (type: `string`):

Use a different name for independent monitoring histories.

## `maxStatusChecks` (type: `integer`):

Recheck missing previously active ads by ID. Extra confirmed observations may exceed maxAds.

## `maxFileSizeMb` (type: `integer`):

Larger files are reported as failed, not falsely archived.

## `maxTotalMediaMb` (type: `integer`):

Shared per-run download budget; skipped variants remain visible in the manifest.

## `maxRequests` (type: `integer`):

Shared cap across source operations, recovered sessions and media downloads. Browser assets are capped separately by maxBrowserRequests.

## `maxRunSeconds` (type: `integer`):

Stop starting new source requests after this budget. Configure Actor timeout above this plus 60 seconds.

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

US Apify residential proxy for public search/details (verified in a small run). Media CDN downloads use a direct connection to control transfer cost.

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

Optional source media filter. Each type uses a separate comparison history.

## `pageSize` (type: `integer`):

Number of source result groups per request. A group can contain multiple ads. This does not change the comparison history scope.

## `requestDelayMs` (type: `integer`):

Minimum spacing between source operations. Recovery waits are separate and longer. All sessions share the request/time budget.

## `sourceMode` (type: `string`):

HTTP uses its selected client and bounded session recovery. Auto can use browser rendering for session/network failures. Plain HTTP source rejection recovery stays on HTTP; login and verification challenges stop.

## `httpBootstrapMode` (type: `string`):

Advanced comparison option. Library mode reads the initial public results before pagination; home preserves the previously validated HTTP path.

## `maxRecoveries` (type: `integer`):

At most two recovery attempts (three sessions total), shared across search and advertiser details. Budget/time limits still apply.

## `recoveryDelayMs` (type: `integer`):

Initial recovery wait; doubles on the second recovery. A longer Retry-After is respected. No attempt starts if the wait exceeds the remaining time budget.

## `maxBrowserRequests` (type: `integer`):

Additional cap for page assets and automatic browser requests. Images, fonts and video loads are blocked; requested creative downloads are handled separately.

## `httpTransport` (type: `string`):

HTTP transport for public search/details. Browser mode is separate. Legacy Got is retained for bounded comparisons.

## `recoverSourceRejections` (type: `boolean`):

After waiting, allow a fresh HTTP proxy/session for a plain 403 or rate-limit response, within maxRecoveries. Honor Retry-After. Login, CAPTCHA, verification challenges and redirects always stop.

## Actor input object example

```json
{
  "keyword": "nike",
  "country": "US",
  "activeStatus": "all",
  "maxAds": 1,
  "archiveMedia": true,
  "includeInstagramFollowers": true,
  "trackChanges": true,
  "historyNamespace": "default",
  "maxStatusChecks": 10,
  "maxFileSizeMb": 10,
  "maxTotalMediaMb": 30,
  "maxRequests": 24,
  "maxRunSeconds": 240,
  "proxyConfiguration": {
    "useApifyProxy": true,
    "apifyProxyGroups": [
      "RESIDENTIAL"
    ],
    "apifyProxyCountry": "US"
  },
  "mediaType": "video",
  "pageSize": 1,
  "requestDelayMs": 2000,
  "sourceMode": "http",
  "httpBootstrapMode": "home",
  "maxRecoveries": 2,
  "recoveryDelayMs": 20000,
  "maxBrowserRequests": 160,
  "httpTransport": "impit",
  "recoverSourceRejections": true
}
```

# Actor output Schema

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

No description

## `runSummary` (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 = {
    "keyword": "nike",
    "country": "US",
    "maxAds": 1,
    "maxFileSizeMb": 10,
    "maxTotalMediaMb": 30,
    "maxRequests": 24,
    "mediaType": "video",
    "pageSize": 1
};

// Run the Actor and wait for it to finish
const run = await client.actor("magenta_courser/meta-ads-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 = {
    "keyword": "nike",
    "country": "US",
    "maxAds": 1,
    "maxFileSizeMb": 10,
    "maxTotalMediaMb": 30,
    "maxRequests": 24,
    "mediaType": "video",
    "pageSize": 1,
}

# Run the Actor and wait for it to finish
run = client.actor("magenta_courser/meta-ads-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 '{
  "keyword": "nike",
  "country": "US",
  "maxAds": 1,
  "maxFileSizeMb": 10,
  "maxTotalMediaMb": 30,
  "maxRequests": 24,
  "mediaType": "video",
  "pageSize": 1
}' |
apify call magenta_courser/meta-ads-library-scraper --silent --output-dataset

```

## MCP server setup

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