# X (Twitter) Ads Library Scraper — Ads Repository & Targeting (`rastriq/x-ads-repository-scraper`) Actor

Scrape the X (Twitter) Ads Library / Ads Repository: every EU ad of any advertiser with impressions, reach, targeting, agency, text, media, landing URL & UTM. Monthly timeline and change monitoring.

- **URL**: https://apify.com/rastriq/x-ads-repository-scraper.md
- **Developed by:** [Rastriq — Structured data from the world](https://apify.com/rastriq) (community)
- **Categories:** Social media
- **Features:** Limited permissions
- **Stats:** 3 total users, 3 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

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

## X (Twitter) Ads Library Scraper — Ads Repository & Targeting

**X (Twitter) Ads Library Scraper** extracts every ad an advertiser ran on X in the European Union from the official [X Ads Repository](https://ads.twitter.com/ads-repository): impressions, reach, the full targeting setup, the ad account (often revealing the media agency) and the complete creative — post text, images and videos, headline, landing page and UTM tags. Use it as an X Ads Library API (Twitter Ads Library) for competitor research, ad intelligence and DSA transparency analysis.

### 🔎 What is X (Twitter) Ads Library Scraper?

Under the EU Digital Services Act, X publishes a repository of ads shown in the EU. The official tool lets you look up one advertiser at a time and shows little more than an embedded post. **X (Twitter) Ads Library Scraper** turns it into structured data you can export, schedule and compare over time:

- 📊 **Performance** — impressions, reach and frequency for every ad and country
- 🎯 **Targeting** — every criterion X discloses (interests, keywords, followers of / lookalikes of accounts, custom audiences, retargeting, TV shows, age, gender, language, OS, geo), grouped by type
- 🏢 **Who's behind it** — ad account name, funding instrument, currency and the inferred agency (e.g. *Spotify - Universal McCann*)
- 🎨 **Creative** — text, language, likes, replies, hashtags, mentions, media (image URLs, MP4 videos with all variants and duration), card type, headline, landing URL, domain and parsed UTM parameters
- 📅 **Delivery timeline** — optional month-by-month impressions: when each ad ran, for how long and how hard
- 🔁 **Monitoring** — run it weekly with a monitor key to get only **new**, **updated** or **removed** ads
- ✅ **Complete results** — no pagination limits: heavy advertisers are split automatically by country and date, and false empty answers from X are re-checked

Typical uses: competitor ad monitoring, media agency pitching, creative benchmarking, campaign tracking by UTM, and academic or compliance research on EU political and commercial advertising.

### 📦 What data does X (Twitter) Ads Library Scraper extract?

| Group | Fields |
|---|---|
| 🆔 Identity | `adKey` (durable id: post × line item × country), `tweetId`, `tweetUrl`, `lineItemId`, `adAccountId`, `country`, `countryName` |
| 👤 Advertiser | `advertiserHandle`, `advertiserId`, `advertiserName`, `advertiserProfileImageUrl`, `advertiserUrl` |
| 🏢 Account | `adAccountName`, `agencyName`, `adAccountDeleted`, `fundingInstrumentType`, `currency`, `approvalStatus` |
| 📊 Metrics | `impressions`, `reach`, `frequency` |
| 📅 Timeline | `impressionsByMonth{}`, `firstActiveMonth`, `lastActiveMonth`, `activeMonths` |
| 🎯 Targeting | `targeting[]`, `targetingByType{}`, `targetingTypes`, `targetingCount`, `targetingSummary` |
| 🎨 Creative | `text`, `lang`, `tweetCreatedAt`, `likeCount`, `replyCount`, `isEdited`, `hashtags`, `mentions`, `urls`, `cashtags`, `media[]`, `mediaCount`, `creativeType`, `headline`, `cardDescription`, `callToAction`, `destinationUrl`, `destinationDomain`, `utm{}`, `app` (id, platform, title, category, rating), `embedHtml` |
| ✍️ Author | `authorName`, `authorHandle`, `authorVerifiedType`, `authorIsBlueVerified`, `authorProfileImageUrl` |
| 🔁 Monitoring | `changeType`, `firstSeen`, `lastSeen`, `contentHash` |
| 🧾 Traceability | `recordType`, `sourceUrl`, `scrapedAt`, `sourceStartDate`, `sourceEndDate`, `countriesQueried`, `metricsWindows`, `creativeFetchStatus`, `qualityFlags[]` |

71 fields per ad. With **One row per creative** you also get `countries`, `lineItemIds`, `impressionsByCountry` and `adRows`.

### 🚀 How to use X (Twitter) Ads Library Scraper

1. Open **X (Twitter) Ads Library Scraper** in Apify Console and click **Try for free**.
2. Add one or more advertisers: `Spotify`, `@amazon` or `https://x.com/Nike`.
3. Choose the countries (all 27 EU countries by default) and the date range (from 2023-08-26).
4. Keep **Fetch creatives** on to get text, media and landing pages.
5. Click **Start** and download the results as JSON, CSV, Excel or via API.
6. Optional: set a **Monitor key** and schedule the Actor weekly to receive only new or changed ads.

### ⚙️ Input parameters

| Parameter | Type | Default | Description |
|---|---|---|---|
| `advertisers` | array | — | X handles or profile URLs (required) |
| `marketPreset` | string | `eu27` | `eu27`, `dach`, `france_benelux`, `southern_europe`, `nordics`, `central_eastern`, `ireland` |
| `countries` | array | — | Custom EU country codes; overrides the preset |
| `startDate` / `endDate` | string | `2023-08-26` / today | `YYYY-MM-DD` or relative (`90 days`) |
| `enrichCreatives` | boolean | `true` | Add text, media, headline, landing URL, UTM |
| `includeEmbedHtml` | boolean | `false` | Add the official X embed code of each post |
| `outputMode` | string | `ads` | `ads` (post × country) or `creatives` (one row per post) |
| `deliveryTimeline` | string | `none` | `monthly` adds impressions per month and first/last active month |
| `sortBy` | string | `impressions-desc` | `impressions-desc`, `reach-desc`, `newest`, `none` |
| `maxAdsPerAdvertiser` | integer | `0` | 0 = no limit |
| `minImpressions` / `minReach` | integer | `0` | Optional filters |
| `searchTerms` | array | — | Keep ads mentioning any of these words |
| `monitorKey` | string | — | Enables change detection across runs |
| `onlyChanges` / `emitRemoved` | boolean | `false` | Output only new/updated ads; add rows for removed ads |
| `emitAdvertiserErrors` | boolean | `false` | Free row for advertisers not found or failed |
| `finalRetryRounds` / `finalRetryWaitSecs` | integer | `1` / `90` | Retry failed parts and failed advertisers at the end of the run |
| `completeness` | string | `standard` | `thorough` = monthly windows, smaller country groups, passes until stable |
| `recheckEmpty` / `extraPasses` | boolean / integer | `true` / `1` | Completeness safeguards (X often answers partially) |

```json
{
  "advertisers": ["Spotify", "@amazon"],
  "marketPreset": "eu27",
  "startDate": "2025-01-01",
  "enrichCreatives": true,
  "monitorKey": "streaming-competitors",
  "onlyChanges": true
}
```

### 📤 Output example

```json
{
  "adKey": "1680891065015107585:42869710:CZ",
  "advertiserHandle": "Spotify",
  "advertiserName": "Spotify",
  "tweetUrl": "https://x.com/Spotify/status/1680891065015107585",
  "country": "CZ",
  "adAccountName": "Spotify - Universal McCann",
  "agencyName": "Universal McCann",
  "currency": "EUR",
  "approvalStatus": "Verified",
  "impressions": 7121,
  "reach": 3710,
  "frequency": 1.919,
  "targetingTypes": ["Geo", "InterestCategory"],
  "targetingByType": {"InterestCategory": ["DJs", "Dance", "Electronic"], "Geo": ["Czech Republic"]},
  "text": "Nejlepší letní hity najdete v playlistu Letní Hity 2023…",
  "lang": "cs",
  "creativeType": "video_website",
  "headline": "Poslouchej Na Spotify",
  "destinationDomain": "spotify.app.link",
  "media": [{"type": "video", "durationMs": 21333, "width": 1080, "height": 1080,
             "videoUrl": "https://video.twimg.com/amplify_video/1680879245730656258/vid/720x720/….mp4"}],
  "changeType": "new",
  "sourceUrl": "https://ads.twitter.com/ads-repository",
  "scrapedAt": "2026-11-11T10:00:00Z",
  "qualityFlags": ["agency_inferred"]
}
```

`qualityFlags` marks records that deserve a second look (`agency_inferred`, `no_targeting_disclosed`, `impressions_below_reach`, `creative_unavailable`…). Nothing is filtered out by default — you decide.

### 💰 How much does it cost to scrape the X Ads Library?

X (Twitter) Ads Library Scraper uses pay-per-event pricing with volume discounts by Apify plan. You pay per ad delivered (creatives included) plus a small start fee per run:

| Apify plan | Price per 1,000 ads | Run start |
|---|---|---|
| Free | $0.30 | $0.001 |
| Starter (Bronze) | $0.25 | $0.0009 |
| Scale (Silver) | $0.20 | $0.0008 |
| Business (Gold) | $0.15 | $0.0007 |
| Enterprise | from $0.12 | $0.0006 |

- **Free plan ($5 credit)**: ~15,000 ads
- **Starter plan ($49/mo)**: ~190,000 ads
- **Advertiser errors** (`emitAdvertiserErrors`) are free rows.

With **monitoring + Only new or changed ads**, weekly runs only charge for ads that are new or changed.

> 💡 **Tip**: Set *Max ads per advertiser* or a narrow date range for a first test.

### 🔗 Related Actors

Build a cross-platform view of competitor advertising with the Rastriq ad intelligence suite:

- [Facebook Ad Library Scraper](https://apify.com/Rastriq/fb-adlibrary-scraper) — Meta ads (Facebook & Instagram)
- [Google Ads Transparency Center Scraper](https://apify.com/Rastriq/google-ads-scraper) — Search, YouTube and Display ads
- [TikTok Ad Library Scraper](https://apify.com/Rastriq/tiktok-ad-library-scraper) — TikTok ads, targeting and reach
- [LinkedIn Ad Library Scraper](https://apify.com/Rastriq/linkedin-ad-library-scraper) — B2B ads on LinkedIn

### ❓ FAQ

**Which ads are included?** Only ads delivered in the EU, which is what X publishes under the Digital Services Act. Ads shown only in the US or other regions are not in the repository. The earliest date is 26 August 2023.

**Can I search by keyword instead of advertiser?** The X Ads Repository only supports lookups by advertiser. Use `searchTerms` to keep ads whose text, headline, landing URL or targeting matches your words.

**How is the agency detected?** Many ad accounts are named `<Brand> - <Agency>`. When that pattern is present, X (Twitter) Ads Library Scraper fills `agencyName` and adds the flag `agency_inferred`.

**What happens with very large advertisers?** X rejects heavy queries with "Over capacity". X (Twitter) Ads Library Scraper automatically splits them — first by country (exact), then by date window. Impressions from contiguous windows add up exactly; reach keeps the highest window value (flags `impressions_summed_across_windows`, `reach_is_max_across_windows`). Parts that still fail are retried at the end of the run after a pause (`finalRetryRounds`); only if they keep failing are the ads flagged `advertiser_partial`. If X answers "over capacity" and then only empty lists for an advertiser, the result is not trusted: the advertiser gets status `unverified_empty` in the `OUTPUT` record (flags `empty_despite_over_capacity`, `empty_not_reverified`), a free `advertiser_error` row is added when `emitAdvertiserErrors` is on, and the run fails if no advertiser could be fetched reliably — rerun it later.

**Why can two runs return different numbers?** X's repository is not deterministic: under load it returns partial or empty lists and rejects heavy queries. X (Twitter) Ads Library Scraper re-asks empty answers, makes an extra pass by default (`extraPasses`) and merges everything by ad key. For very large advertisers use **Completeness mode: Thorough**. The `OUTPUT` record of each run lists queries, splits and recovered answers per advertiser.

**Why is reach not summed in creatives mode?** Reach is unique users per row; summing across countries overestimates it. `reachIsSumAcrossRows` tells you when that happens.

**Is it legal to scrape the X Ads Repository?** The Actor only reads data X publishes for transparency purposes and accesses no private accounts. You are responsible for complying with X's terms and applicable laws (including GDPR) in how you use the data. Personal data is not collected beyond public advertiser profiles.

**Something broke?** Open an issue in the Actor's **Issues** tab — we usually reply within 24 hours.

# Actor input Schema

## `advertisers` (type: `array`):

X handles of the advertisers. Accepts 'Spotify', '@Spotify' or 'https://x.com/Spotify'. The repository searches by advertiser only (no keyword search) — use 'Filter by text' below to narrow results.

## `marketPreset` (type: `string`):

Group of EU countries to query. Ignored if you fill in 'Custom countries'.

## `countries` (type: `array`):

Optional list of EU country codes (ISO-2, e.g. ES, FR, DE). Non-EU codes are ignored.

## `startDate` (type: `string`):

Start of the period (YYYY-MM-DD) or a relative value like '90 days'. Earliest available: 2023-08-26.

## `endDate` (type: `string`):

End of the period (YYYY-MM-DD). Empty = today.

## `enrichCreatives` (type: `boolean`):

Add the post text, language, likes, media (images/videos with MP4 URLs), card headline, landing URL, domain and UTM tags. Adds ~1 request per unique post.

## `includeEmbedHtml` (type: `boolean`):

Add the official X embed code (oEmbed blockquote) of each post — ready to paste into dashboards or reports. Requires 'Fetch creatives'.

## `outputMode` (type: `string`):

'One row per ad' = one row per post × line item × country (as published by X). 'One row per creative' = one row per post with impressions summed across countries and impressionsByCountry.

## `deliveryTimeline` (type: `string`):

'Monthly' queries the repository month by month and adds impressionsByMonth, firstActiveMonth, lastActiveMonth and activeMonths to each ad (when it ran and how hard). Uses ~1 request per month per advertiser.

## `completeness` (type: `string`):

'Standard' = 6-month windows + the extra passes below. 'Thorough' = monthly windows, groups of 9 countries and up to 6 passes until results stop changing — for very large advertisers; can take several minutes per advertiser.

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

Order of results within each advertiser (applied before 'Max ads per advertiser').

## `maxAdsPerAdvertiser` (type: `integer`):

0 = no limit.

## `minImpressions` (type: `integer`):

Only keep ads with at least this many impressions. 0 = keep all.

## `minReach` (type: `integer`):

Only keep ads with at least this reach. 0 = keep all.

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

Keep only ads whose text, headline, landing URL, ad account or targeting contains any of these words (case-insensitive). Works best with 'Fetch creatives' on.

## `monitorKey` (type: `string`):

Any name (e.g. 'my-competitors'). When set, results are compared with previous runs using the same key: each row gets changeType (new / updated / unchanged), firstSeen and lastSeen.

## `onlyChanges` (type: `boolean`):

With a monitor key: output only new and updated ads (you are charged only for those).

## `emitRemoved` (type: `boolean`):

With a monitor key: add a row with changeType 'removed' for ads that were seen before and are no longer returned.

## `emitAdvertiserErrors` (type: `boolean`):

Add a free row (recordType 'advertiser_error') for advertisers not found or that failed, so pipelines can track them.

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

Not needed normally. Enable only if you get repeated errors.

## `finalRetryRounds` (type: `integer`):

X's capacity changes minute to minute. Parts that still fail (and advertisers that failed completely) are retried at the end of the run, after a pause. Advertisers with failed parts are delivered after the retry, so their data is complete when possible. 0 = off.

## `finalRetryWaitSecs` (type: `integer`):

Wait before retrying, so X's backend can recover. Skipped automatically if the run is close to its timeout.

## `repoConcurrency` (type: `integer`):

Parallel queries to the repository for heavy advertisers.

## `maxConcurrency` (type: `integer`):

Parallel requests when fetching creatives.

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

Pause between requests to the repository (randomized ±30%).

## `maxRetries` (type: `integer`):

Retries for temporary errors (429/5xx) before giving up on a request.

## `recheckEmpty` (type: `boolean`):

X occasionally returns an empty list by mistake. When on, every empty answer is queried once more. Recommended.

## `extraPasses` (type: `integer`):

X's repository often returns a partial list on the first try. Each extra pass re-asks every slice (with a different request so it isn't served from cache) and merges new ads. Stops early after 2 passes that add nothing. 1 = recommended; more = slower but more complete.

## Actor input object example

```json
{
  "advertisers": [
    "Spotify",
    "amazon"
  ],
  "marketPreset": "eu27",
  "startDate": "2023-08-26",
  "enrichCreatives": true,
  "includeEmbedHtml": false,
  "outputMode": "ads",
  "deliveryTimeline": "none",
  "completeness": "standard",
  "sortBy": "impressions-desc",
  "maxAdsPerAdvertiser": 0,
  "minImpressions": 0,
  "minReach": 0,
  "onlyChanges": false,
  "emitRemoved": false,
  "emitAdvertiserErrors": false,
  "finalRetryRounds": 1,
  "finalRetryWaitSecs": 90,
  "repoConcurrency": 2,
  "maxConcurrency": 3,
  "requestDelayMs": 500,
  "maxRetries": 4,
  "recheckEmpty": true,
  "extraPasses": 1
}
```

# Actor output Schema

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

No description

## `creatives` (type: `string`):

No description

## `targeting` (type: `string`):

No description

## `allFields` (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 = {
    "advertisers": [
        "Spotify",
        "amazon"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("rastriq/x-ads-repository-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 = { "advertisers": [
        "Spotify",
        "amazon",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("rastriq/x-ads-repository-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 '{
  "advertisers": [
    "Spotify",
    "amazon"
  ]
}' |
apify call rastriq/x-ads-repository-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rastriq/x-ads-repository-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/X6jyMgMQvUbGJ6sh2/builds/CRrJOo6o4dLDQewVO/openapi.json
