跳到正文
DEV Community· Viktor·· 1 小時前AI 評分58

如何用 Node.js 擷取 LinkedIn Ad Library:整理曝光區間、國家分佈及競品報告(2026)

How to Scrape LinkedIn Ad Library with Node.js: Impression Ranges, Country Splits, and a Competitor Report (2026)

AI 導讀

作者提供約 200 行、沒有 npm 依賴的 Node.js 腳本 liads.mjs,透過 ScrapeAtlas 取得 LinkedIn Ad Library 廣告數據,建立 JSONL 快照、競品報告並比較快照變化。

正文

"LinkedIn ad library" gets about 5,400 US searches a month. Most of those people want the same thing: see what a competitor is running on LinkedIn, how big each campaign was, and who it was aimed at. Then they want to check again next week without clicking through dozens of ad cards. LinkedIn's Ad Library is public and needs no login. But it's a browse-only website, and the most useful numbers only show up for some ads.

This post builds liads.mjs, a ~200-line Node.js script with no npm dependencies, that turns the library into data you can work with:

  1. pull saves every ad for one company (filtered by country and date) to a JSONL snapshot
  2. report turns snapshots into a competitor summary: formats, impression ranges, where impressions actually landed, which targeting facets were used, and the biggest ads
  3. diff compares two snapshots, so a weekly cron job can tell you what's new

Everything below ran on November 30, 2026 (04:00-05:00 UTC) with Node.js 24 on a Linux server. The examples compare HubSpot, Salesforce and Pipedrive in the DACH countries (Germany, Austria, Switzerland), plus Notion in the US and in the EU.

Read this first: LinkedIn's terms prohibit scraping. Section 8.2 of the LinkedIn User Agreement (effective November 3, 2025) says you may not "develop, support or use software, devices, scripts, robots or any other means or processes (such as crawlers, browser plugins and add-ons or any other technology) to scrape or copy the Services". linkedin.com/robots.txt ends with User-agent: * / Disallow: /. The Ad Library is a public transparency tool, but the terms still apply to it. Review them and the legal risk for your use case and country before you run anything here. If you can get it, use the official LinkedIn Ad Library API (api.linkedin.com/rest/adLibrary?q=criteria). It's a separate product you request for an app in the LinkedIn Developer Portal, and LinkedIn reviews each request. Keep volumes small, and stick to company advertisers as this post does. Don't build profiles of the individual people who show up as "posters" on thought-leader ads.

Step 1: What a plain Node.js script gets

Before writing a parser, I checked what LinkedIn returns to an ordinary fetch with a desktop Chrome user agent, and what the official API says without a token:

// probe.mjs - what a plain Node.js script gets from LinkedIn's Ad Library and its official API.
const UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
const targets = [
  ["robots.txt", "https://www.linkedin.com/robots.txt", {}],
  ["library search", "https://www.linkedin.com/ad-library/search?accountOwner=HubSpot&countries=DE", {}],
  ["ad detail page", "https://www.linkedin.com/ad-library/detail/1643987424", {}],
  ["official API, no token", "https://api.linkedin.com/rest/adLibrary?q=criteria&advertiser=HubSpot&count=25",
    { "X-Restli-Protocol-Version": "2.0.0", "LinkedIn-Version": "202610" }],
];
for (const [label, url, extra] of targets) {
  const res = await fetch(url, { headers: { "user-agent": UA, "accept-language": "en-US,en;q=0.9", ...extra } });
  const body = await res.text();
  const hint = body.match(/<title>([^<]*)<\/title>/)?.[1]
    ?? body.match(/User-agent: \*\nDisallow: .*/)?.[0].replace("\n", " / ") ?? body.slice(0, 90);
  console.log(`${label.padEnd(23)} ${res.status}  ${String(body.length).padStart(6)} B  ${hint.trim()}`);
}
robots.txt              200  120235 B  User-agent: * / Disallow: /
library search          403    4557 B  Attention Required! | Cloudflare
ad detail page          403    4557 B  Attention Required! | Cloudflare
official API, no token  401     105 B  {"status":401,"serviceErrorCode":65604,"code":"EMPTY_ACCESS_TOKEN","message":"Empty oauth2

From my server, both library pages came back as Cloudflare's "Attention Required!" block page (HTTP 403, 4.5 KB), not the ad cards. A home connection may get further. But this is the first wall you'll hit if you run a scraper from a cloud VM or a CI job, and retrying from the same IP doesn't help. The official endpoint exists and answers immediately. It just wants an OAuth token from an app that was approved for the Ad Library API product.

So there are two real options:

  • Official API: apply for the Ad Library API product. If you're approved, the response has the targeting facets, impression ranges and per-country splits in structured form. Third-party write-ups say it doesn't include the ad text or image (you get adUrl back), and that it's throttled per minute.
  • A data API that reads the public pages for you. That's what the rest of this post uses.

Step 2: What the library actually publishes (and the EU catch)

Every ad card shows the advertiser, the "paid for by" entity, the format and the creative. The interesting fields are impressions, run dates, a per-country split and targeting, and LinkedIn only publishes those for ads targeted at the EU (that's what the EU Digital Services Act requires). A US-only campaign shows you the creative and nothing else.

Here's one HubSpot ad after the script below has normalized it (country list shortened):

{
  "id": "1643987424",
  "url": "https://www.linkedin.com/ad-library/detail/1643987424",
  "advertiser": "HubSpot",
  "companyId": "68529",
  "paidForBy": "HubSpot, Inc.",
  "adType": "Video Ad",
  "start": "2026-11-17",
  "end": "2026-11-30",
  "days": 14,
  "impressions": {
    "label": "50k-100k",
    "lo": 50000,
    "hi": 100000
  },
  "countries": [
    {
      "country": "Germany",
      "share": 1
    },
    {
      "country": "India",
      "share": 0.005
    },
    {
      "country": "United Kingdom",
      "share": 0.005
    },
    {
      "...": "19 more rows"
    }
  ],
  "targeting": {
    "language": "Targeting includes English",
    "location": "Targeting includes Germany",
    "audience": "Exclusion targeting applied",
    "company": "Exclusion targeting applied"
  },
  "text": "Das Marketing Team hinter Ihrem Marketing Team.",
  "cta": "Request Demo",
  "query": {
    "companyId": "68529",
    "countries": "DE,AT,CH",
    "dateOption": "last-30-days"
  },
  "pulledAt": "2026-11-30T04:12:05.597Z"
}

Three things to note before writing any code:

  • Impressions are ranges, not numbers: "<\u200a1k", "1k-5k", "500k-1M", "> 1M". That \u200a is a hair space, so a check like label === "< 1k" (normal space) never matches. Any sum you compute is a range too.
  • Country shares are rounded and don't add up to 100%. This ad is "100%" Germany plus eight countries at "< 1%".
  • Targeting is mostly a yes/no flag. You see the locations and languages. For company, job, audience or interest targeting you only learn that it was used: "Exclusion targeting applied", never the list.

Step 3: The client and the parsers

I fetch the library through ScrapeAtlas*, which has /v1/linkedin/ads/search (one library page, with each card filled in from its detail page) and /v1/linkedin/ad (one ad by ID). Each successful call costs 1 credit, and failed calls are free. If you get access to the official API, swap sa() for your own client and keep everything below it.

The first part of liads.mjs is the HTTP helper plus the two parsers for those human-formatted strings:

// liads.mjs - LinkedIn Ad Library competitor report in Node.js (no npm dependencies).
// Node 21+ (built-in fetch, Map.groupBy). Read LinkedIn's User Agreement first: section 8.2 bans scraping.
//
//   node liads.mjs pull --company-id 68529 --countries DE,AT,CH --date last-30-days --pages 4
//   node liads.mjs report data/68529_DE-AT-CH_20261130-0405.jsonl [more.jsonl ...]
//   node liads.mjs diff data/old.jsonl data/new.jsonl
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";

const API = "https://api.scrapeatlas.com/v1/linkedin";
const KEY = process.env.SCRAPEATLAS_API_KEY ?? "";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let credits = 0;

async function sa(path, params) {
  const url = `${API}/${path}?${new URLSearchParams(params)}`;
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(url, { headers: { "x-api-key": KEY } });
    const body = await res.json().catch(() => ({}));
    if (res.ok && body.success) { credits++; return body; }
    if (attempt < 3 && (res.status === 429 || res.status >= 500)) { await sleep(3000 * attempt); continue; }
    const f = body.failure ?? {};
    throw new Error(`${path} -> HTTP ${res.status} ${f.code ?? ""} ${f.message ?? ""}`.trim());
  }
}

// ---------- parsing the strings LinkedIn shows to humans ----------
const UNIT = { k: 1e3, M: 1e6, B: 1e9 };
const num = (s) => { const m = s.trim().match(/^([\d.]+)\s*([kMB]?)$/); return m ? +m[1] * (UNIT[m[2]] ?? 1) : NaN; };

// "1k-5k" -> [1000, 5000]; "<\u200a1k" -> [0, 1000]; "> 1M" -> [1000000, null] (open-ended)
export function parseRange(label) {
  if (!label) return null;
  const s = label.replace(/[\u200a\u2009\u00a0\s]/g, "");
  if (s.startsWith("<")) return [0, num(s.slice(1))];
  if (s.startsWith(">")) return [num(s.slice(1)), null];
  if (s.endsWith("+")) return [num(s.slice(0, -1)), null];
  const [lo, hi] = s.split("-").map(num);
  return Number.isNaN(lo) || Number.isNaN(hi) ? null : [lo, hi];
}

// "28%" -> 0.28; "< 1%" -> 0.005 (we only know it is under 1%, so take the middle)
export function parseShare(label) {
  const s = label.replace(/[\u200a\u2009\u00a0\s]/g, "");
  if (s.startsWith("<")) return parseFloat(s.slice(1)) / 200;
  return parseFloat(s) / 100;
}

const clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
const day = (iso) => (iso ? iso.slice(0, 10) : null);

function normalize(ad, query) {
  const imp = parseRange(ad.totalImpressions);
  const days = ad.startDate && ad.endDate ? Math.round((Date.parse(ad.endDate) - Date.parse(ad.startDate)) / 864e5) + 1 : null;
  return {
    id: ad.id,
    url: ad.url,
    advertiser: ad.advertiser,
    companyId: ad.advertiserLinkedinPage?.match(/company\/(\d+)/)?.[1] ?? null,
    paidForBy: ad.paidForBy,
    adType: ad.adType,
    start: day(ad.startDate),
    end: day(ad.endDate),
    days,
    impressions: ad.totalImpressions ? { label: clean(ad.totalImpressions), lo: imp?.[0] ?? null, hi: imp?.[1] ?? null } : null,
    countries: (ad.impressionsByCountry ?? []).map((c) => ({ country: c.country, share: parseShare(c.impressions) })),
    targeting: Object.fromEntries(Object.entries(ad.targetingDetails ?? {}).map(([k, v]) => [k, clean(v)])),
    text: clean(ad.headline || ad.description).slice(0, 90),
    cta: ad.cta,
    query,
    pulledAt: new Date().toISOString(),
  };
}

normalize() keeps targetingDetails rather than targeting. The two fields hold the same facets, but in targeting long location lists come back with raw markup whitespace and a collapsed "and\n \n 36 others\n" in the middle. companyId comes from the advertiser's page URL. It matters in Step 4.

A test with labels copied from real responses (node --test):

// node --test  (checks the two parsers against labels copied from real responses)
import test from "node:test";
import assert from "node:assert/strict";
import { parseRange, parseShare } from "./liads.mjs";

test("impression ranges", () => {
  assert.deepEqual(parseRange("1k-5k"), [1000, 5000]);
  assert.deepEqual(parseRange("500k-1M"), [500000, 1000000]);
  assert.deepEqual(parseRange("<\u200a1k"), [0, 1000]);
  assert.deepEqual(parseRange("> 1M"), [1000000, null]);
  assert.equal(parseRange(null), null);
});

test("country shares", () => {
  assert.equal(parseShare("28%"), 0.28);
  assert.equal(parseShare("100%"), 1);
  assert.equal(parseShare("<\u200a1%"), 0.005);
});
✔ impression ranges (2.242563ms)
✔ country shares (0.259242ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

Step 4: Pulling every ad for one company

// ---------- pull ----------
function flags(argv) {
  const out = {};
  for (let i = 0; i < argv.length; i++) if (argv[i].startsWith("--")) out[argv[i].slice(2)] = argv[i + 1]?.startsWith("--") || argv[i + 1] === undefined ? true : argv[++i];
  return out;
}

async function pull(argv) {
  const f = flags(argv);
  if (!KEY) throw new Error("set SCRAPEATLAS_API_KEY");
  const query = {};
  if (f["company-id"]) query.companyId = f["company-id"];
  if (f.company) query.company = f.company;
  if (f.keyword) query.keyword = f.keyword;
  if (f.countries) query.countries = f.countries;
  query.dateOption = f.date ?? "last-30-days";
  const pages = Number(f.pages ?? 1);
  const rows = new Map();
  let token = null, failed = [], total = null, broke = false;
  for (let page = 1; page <= pages; page++) {
    let r;
    try {
      r = await sa("ads/search", token ? { ...query, paginationToken: token } : query);
    } catch (e) { // a failed page is free; keep what we have instead of losing the whole run
      console.log(`page ${page}: ${e.message} - stopping, keeping ${rows.size} ads`);
      broke = true;
      break;
    }
    total ??= r.totalAds;
    for (const ad of r.ads) rows.set(ad.id, normalize(ad, query));
    failed.push(...r.failedAds.map((x) => x.id));
    console.log(`page ${page}: ${r.ads.length} ads, ${r.failedAds.length} failed ${JSON.stringify(r.failedAds.map((x) => x.code))}` +
      `${r.totalAds != null ? `, library total ${r.totalAds}` : ""} | ${r.status} ${JSON.stringify(r.coverage.warnings)}`);
    token = r.paginationToken;
    if (r.isLastPage || !token) break;
    await sleep(1500);
  }
  // deep pages can fail (we saw page 4 return 502 every time). Read the tail from the other end instead.
  if (broke && total && rows.size + failed.length < total) {
    const r = await sa("ads/search", { ...query, sortOrder: "ASCENDING" });
    const fresh = r.ads.filter((ad) => !rows.has(ad.id));
    for (const ad of fresh) rows.set(ad.id, normalize(ad, query));
    failed.push(...r.failedAds.map((x) => x.id).filter((id) => !rows.has(id)));
    console.log(`oldest-first page: ${r.ads.length} ads, ${fresh.length} not seen yet -> ${rows.size} of ${total}`);
  }
  // ads whose detail page failed upstream come back as ids only: fetch them one by one
  for (const id of failed) {
    await sleep(2000);
    try {
      const ad = await sa("ad", { adId: id });
      rows.set(id, normalize(ad, query));
      console.log(`retried ${id}: ok (${ad.adType}, ${ad.totalImpressions ?? "no impressions"})`);
    } catch (e) { console.log(`retried ${id}: ${e.message}`); }
  }
  mkdirSync("data", { recursive: true });
  const label = query.companyId ?? (query.company ?? query.keyword).replace(/\W+/g, "-").toLowerCase();
  const stamp = new Date().toISOString().slice(0, 16).replace(/[-:]/g, "").replace("T", "-"); // 20261130-0405 (UTC)
  const file = `data/${label}_${(query.countries ?? "ALL").replaceAll(",", "-")}_${stamp}.jsonl`;
  writeFileSync(file, [...rows.values()].map((r) => JSON.stringify(r)).join("\n") + "\n");
  console.log(`saved ${rows.size} ads -> ${file} (${credits} credits)`);
}

Run it for HubSpot in DACH over the last 30 days:

export SCRAPEATLAS_API_KEY=...
node liads.mjs pull --company-id 68529 --countries DE,AT,CH --date last-30-days --pages 4
page 1: 24 ads, 0 failed [], library total 81 | success []
page 2: 24 ads, 0 failed [] | success []
page 3: 24 ads, 0 failed [] | success []
page 4: ads/search -> HTTP 502 unsupported_page The public page structure is not supported. - stopping, keeping 72 ads
oldest-first page: 23 ads, 9 not seen yet -> 81 of 81
saved 81 ads -> data/68529_DE-AT-CH_20261130-0412.jsonl (4 credits)

Two things in that output shaped the code:

  • Page 4 failed every time. Pages 1-3 worked, and the fourth page returned 502 unsupported_page on three tries in a row. The same thing happened with Salesforce. Because the failure comes from one specific deep page, the script asks for page 1 sorted oldest first (sortOrder=ASCENDING). That page held exactly the 9 ads still missing, so the snapshot has all 81 the library reports. Without the fallback, the first version of this script lost the whole run on page 4.
  • Pages hold 24 cards, not 25, and now and then one card's detail page is rate-limited upstream (failedAds: [{ code: "upstream_rate_limited" }]). The script fetches those one at a time from /v1/linkedin/ad at the end. That was 1 extra credit in the Salesforce run:
page 1: 24 ads, 0 failed [], library total 78 | partial ["creative_format_incomplete","document_preview_only"]
page 2: 23 ads, 1 failed ["upstream_rate_limited"] | partial ["creative_format_incomplete","first_creative_variant_only","ad_details_unavailable"]
page 3: 24 ads, 0 failed [] | partial ["document_preview_only","first_creative_variant_only"]
page 4: ads/search -> HTTP 502 unsupported_page The public page structure is not supported. - stopping, keeping 71 ads
oldest-first page: 24 ads, 6 not seen yet -> 77 of 78
retried 1669916896: ok (Job Ad, 5k-10k)
saved 78 ads -> data/3185_DE-AT-CH_20261130-0413.jsonl (5 credits)

Why --company-id and not --company: the name filter is a substring match on advertiser names. --company HubSpot returned 20 ads from HubSpot and 4 from a German HubSpot partner agency on the very first page:

== HubSpot (company 68529) - 20 ads, 20 with EU impression data
== made2GROW GmbH | HubSpot Platin Partner (company 11573825) - 4 ads, 4 with EU impression data

You can find the numeric ID in any of a company's ads (advertiserLinkedinPage, .../company/68529), or on its LinkedIn page.

Step 5: The competitor report

// ---------- report ----------
const load = (file) => readFileSync(file, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l));
const fmt = (n) => (n >= 1e6 ? `${+(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : String(Math.round(n)));
const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor((s.length - 1) / 2)] : null; };
// midpoint of the range; for "> 1M" we only know the floor, so use it (an underestimate)
const mid = (r) => (!r.impressions ? 0 : r.impressions.hi == null ? r.impressions.lo : (r.impressions.lo + r.impressions.hi) / 2);
const regionName = new Intl.DisplayNames(["en"], { type: "region" });

function report(files) {
  // several snapshots of the same company may be passed: keep the newest copy of each ad
  const rows = [...new Map(files.flatMap(load).map((r) => [r.id, r])).values()];
  const groups = Map.groupBy(rows, (r) => r.companyId);
  const sorted = [...groups.entries()].sort((a, b) => b[1].length - a[1].length);
  for (const [companyId, ads] of sorted) {
    const eu = ads.filter((r) => r.impressions);
    const lo = eu.reduce((s, r) => s + r.impressions.lo, 0), hi = eu.reduce((s, r) => s + (r.impressions.hi ?? r.impressions.lo), 0);
    const open = eu.some((r) => r.impressions.hi == null) ? "+" : "";
    console.log(`\n== ${ads[0].advertiser} (company ${companyId}) - ${ads.length} ads, ${eu.length} with EU impression data`);
    if (ads[0].query.companyId && ads[0].query.companyId !== companyId) console.log("   (not the company you asked for)");
    const types = Object.entries(Object.groupBy(ads, (r) => r.adType)).map(([t, xs]) => `${t} ${xs.length}`).join(", ");
    console.log(`   formats: ${types}`);
    const payers = Object.entries(Object.groupBy(ads, (r) => r.paidForBy ?? "(not shown)")).map(([p, xs]) => `${p} ${xs.length}`).join(", ");
    console.log(`   paid for by: ${payers}`);
    if (!eu.length) { console.log("   no impressions, dates or targeting: LinkedIn only publishes those for ads targeted at the EU"); continue; }
    console.log(`   impressions: ${fmt(lo)}-${fmt(hi)}${open} total (midpoint ${fmt(eu.reduce((s, r) => s + mid(r), 0))}), median run ${median(eu.map((r) => r.days))} days`);

    const byCountry = {};
    for (const r of eu) {
      // "100%" plus a few "< 1%" rows adds up to more than 100%, so rescale each ad to 1
      const sum = r.countries.reduce((s, c) => s + c.share, 0) || 1;
      for (const c of r.countries) byCountry[c.country] = (byCountry[c.country] ?? 0) + (mid(r) * c.share) / sum;
    }
    const total = Object.values(byCountry).reduce((a, b) => a + b, 0);
    console.log(`   est. impressions by country: ${Object.entries(byCountry).sort((a, b) => b[1] - a[1]).slice(0, 6)
      .map(([c, v]) => `${c} ${fmt(v)} (${Math.round((100 * v) / total)}%)`).join(", ")}`);

    const asked = (ads[0].query.countries ?? "").split(",").filter(Boolean).map((c) => regionName.of(c));
    if (asked.length) {
      const outside = Object.entries(byCountry).filter(([c]) => !asked.includes(c)).reduce((s, [, v]) => s + v, 0);
      console.log(`   served outside ${asked.join("/")}: ${Math.round((100 * outside) / total)}% of estimated impressions`);
    }
    const facets = {};
    for (const r of eu) for (const k of Object.keys(r.targeting)) facets[k] = (facets[k] ?? 0) + 1;
    console.log(`   targeting facets: ${Object.entries(facets).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${k} ${Math.round((100 * n) / eu.length)}%`).join(", ")}`);

    console.log("   biggest ads:");
    for (const r of [...eu].sort((a, b) => mid(b) - mid(a) || b.days - a.days).slice(0, 5))
      console.log(`     ${r.id}  ${r.impressions.label.padEnd(9)} ${String(r.days).padStart(3)}d  ${r.adType.padEnd(15)} ${r.text.slice(0, 55)}`);
  }
}

Two estimates in there are worth explaining. Impressions by country multiplies each ad's range midpoint by its country shares, after rescaling the shares so each ad sums to 1. "Served outside" compares that against the countries you queried. To turn DE into "Germany" it uses Intl.DisplayNames, which is built into Node, so there's no lookup table to maintain. Both are estimates built on ranges, so read them as "roughly", not as accounting.

node liads.mjs report data/68529_DE-AT-CH_20261130-0412.jsonl data/3185_DE-AT-CH_20261130-0413.jsonl data/pipedrive_DE-AT-CH_20261130-0407.jsonl

== HubSpot (company 68529) - 81 ads, 81 with EU impression data
   formats: Single Image Ad 38, Video Ad 39, Message Ad 4
   paid for by: HubSpot, Inc. 81
   impressions: 11.2M-18M+ total (midpoint 14.6M), median run 25 days
   est. impressions by country: Germany 12.1M (83%), Switzerland 330k (2%), Austria 262k (2%), United Kingdom 101k (1%), United States 66k (0%), Spain 61k (0%)
   served outside Germany/Austria/Switzerland: 13% of estimated impressions
   targeting facets: language 100%, location 100%, company 94%, audience 88%, job 75%
   biggest ads:
     1188193183  > 1M      271d  Single Image Ad ChatGPT-Playbook (inkl. 84 kostenlosen Prompt-Vorlagen)
     1189393163  > 1M      271d  Single Image Ad ChatGPT-Playbook (inkl. 84 kostenlosen Prompt-Vorlagen)
     1552431773  500k-1M    61d  Video Ad        Unfassbar cool und umsatzstark.
     1606043834  500k-1M    41d  Video Ad        Ein CRM – clever und selbst aktualisierend.
     1605968824  500k-1M    40d  Video Ad        Ein CRM – clever und selbst aktualisierend.

== Salesforce (company 3185) - 78 ads, 71 with EU impression data
   formats: Spotlight Ad 6, Single Image Ad 27, Document Ad 11, Message Ad 12, Carousel Ad 5, Event Ad 4, Job Ad 12, Follow Company Ad 1
   paid for by: Salesforce, Inc. 39, Iprospect.com Inc. 35, (not shown) 4
   impressions: 9.7M-11M+ total (midpoint 10.3M), median run 24 days
   est. impressions by country: India 2.6M (25%), Egypt 955k (9%), United States 864k (8%), Israel 462k (4%), Germany 342k (3%), Turkey 189k (2%)
   served outside Germany/Austria/Switzerland: 96% of estimated impressions
   targeting facets: location 100%, company 96%, job 94%, language 89%, audience 39%, member interests and traits 25%, education 23%
   biggest ads:
     592525104  > 1M      635d  Job Ad          %FIRSTNAME%, explore jobs at Salesforce that match your
     626149993  > 1M      635d  Job Ad          %FIRSTNAME%, explore jobs at Salesforce that match your
     626143343  > 1M      635d  Job Ad          %FIRSTNAME%, explore jobs at Salesforce that match your
     641684796  > 1M      631d  Job Ad          %FIRSTNAME%, explore jobs at Salesforce that match your
     1067805256  > 1M      261d  Follow Company Ad %FIRSTNAME%, explore relevant opportunities with Salesf

== Pipedrive (company 1876917) - 2 ads, 2 with EU impression data
   formats: Job Ad 2
   paid for by: (not shown) 2
   impressions: 250k-350k total (midpoint 300k), median run 1007 days
   est. impressions by country: United States 42k (14%), United Kingdom 29k (10%), Portugal 16k (5%), India 15k (5%), Estonia 15k (5%), Germany 12k (4%)
   served outside Germany/Austria/Switzerland: 95% of estimated impressions
   targeting facets: location 100%
   biggest ads:
     335934804  150k-200k 1066d  Job Ad          %FIRSTNAME%, explore jobs at Pipedrive that match your 
     362901634  100k-150k 1007d  Job Ad          %FIRSTNAME%, explore jobs at Pipedrive that match your 

And Notion, once for the US and once for France, Germany and the Netherlands (one page each):


== Notion (company 30898036) - 24 ads, 0 with EU impression data
   formats: Event Ad 2, Document Ad 22
   paid for by: Notion Labs, Inc. 24
   no impressions, dates or targeting: LinkedIn only publishes those for ads targeted at the EU

== Notion (company 30898036) - 24 ads, 24 with EU impression data
   formats: Document Ad 24
   paid for by: Notion Labs, Inc. 24
   impressions: 41k-134k total (midpoint 88k), median run 7 days
   est. impressions by country: France 44k (50%), Germany 17k (20%), Netherlands 14k (16%), Switzerland 5k (6%), Belgium 5k (6%), Austria 2k (2%)
   served outside Germany/France/Netherlands: 15% of estimated impressions
   targeting facets: language 100%, location 100%, audience 100%, company 100%, job 100%
   biggest ads:
     1694492056  10k-20k     7d  Document Ad     Ramp built 300+ Custom Agents in Notion to help teams s
     1694397946  5k-10k      7d  Document Ad     Your team is buried in busywork: answering the same Sla
     1694492926  5k-10k      7d  Document Ad     🌍 New global research from 6,000+ professionals across
     1694472536  5k-10k      7d  Document Ad     Learn the 5 critical jobs AI should actually solve for 
     1694453016  1k-5k       7d  Document Ad     Ramp built 300+ Custom Agents in Notion to help teams s

What the numbers say

  • HubSpot runs a German campaign, built in two languages. 81 ads, about 83% of estimated impressions in Germany, 37 ads targeted at Deutsch speakers and 44 at English speakers, and almost all of them use company (94%) and audience (88%) targeting, mostly as exclusions (66 and 59 ads). My guess is existing customers and competitors. Video makes up about half of the ads, and 7 of the 9 ads with 500k+ impressions. The two biggest are a ChatGPT playbook lead magnet that has been running for 271 days.
  • "countries=DE,AT,CH" doesn't mean "shown in DACH". Salesforce's 78 matching ads put an estimated 96% of their impressions outside Germany, Austria and Switzerland. India alone is 25%. The filter matches the ad's targeting (one event ad targeted a list running from Peru and Brazil to India and Vietnam, with Germany and Switzerland somewhere in the middle), not where impressions ended up. If you want "ads mainly aimed at Germany", filter on the country split yourself.
  • Payer is not always the advertiser. 35 of Salesforce's ads show paidForBy: "Iprospect.com Inc.", a media agency, and 4 show none at all. Group by payer if you're tracking agencies, and by companyId if you're tracking brands.
  • "Last 30 days" includes always-on ads. Pipedrive's only two matches are job ads that started in 2023 and 2024 and are still running. Salesforce's top five by impressions are job and follow-company ads that ran 261-635 days. The impression range is lifetime, so a 600-day ad will always outrank a fresh campaign. Split those out (for example days > 90) before you compare "this month's" spend.
  • US campaigns are invisible beyond the creative. 596 Notion ads match the US filter, and the 24 newest have no dates, impressions or targeting. Same advertiser, same document-ad format, EU filter: all 24 have data, and France takes half the impressions. If a competitor only advertises in the US, the library can show you their messaging but not their reach.

Step 6: Tracking changes week to week

// ---------- diff ----------
function diff(oldFile, newFile) {
  const a = new Map(load(oldFile).map((r) => [r.id, r])), b = new Map(load(newFile).map((r) => [r.id, r]));
  const added = [...b.values()].filter((r) => !a.has(r.id));
  const gone = [...a.values()].filter((r) => !b.has(r.id));
  const grew = [...b.values()].filter((r) => a.has(r.id) && a.get(r.id).impressions?.label !== r.impressions?.label);
  console.log(`${added.length} new, ${gone.length} no longer listed, ${grew.length} changed impression range`);
  for (const r of added) console.log(`  + ${r.id} ${r.start} ${r.adType} ${r.impressions?.label ?? "-"}  ${r.text.slice(0, 50)}`);
  for (const r of grew) console.log(`  ~ ${r.id} ${a.get(r.id).impressions?.label} -> ${r.impressions?.label}`);
  for (const r of gone) console.log(`  - ${r.id} last seen ${r.pulledAt.slice(0, 10)}  ${r.text.slice(0, 50)}`);
}

const [cmd, ...rest] = process.argv.slice(2);
if (cmd === "pull") await pull(rest);
else if (cmd === "report") report(rest);
else if (cmd === "diff") diff(rest[0], rest[1]);
else if (cmd) console.log("usage: node liads.mjs pull|report|diff ...");

I pulled HubSpot again 31 minutes after the first snapshot (04:43 UTC) and diffed the two:

page 1: 24 ads, 0 failed [], library total 81 | success []
page 2: 22 ads, 2 failed ["upstream_rate_limited","upstream_rate_limited"] | partial ["ad_details_unavailable"]
page 3: 24 ads, 0 failed [] | success []
page 4: ads/search -> HTTP 502 unsupported_page The public page structure is not supported. - stopping, keeping 70 ads
oldest-first page: 24 ads, 9 not seen yet -> 79 of 81
retried 1638309234: ok (Video Ad, 200k-300k)
retried 1593005923: ok (Message Ad, < 1k)
saved 81 ads -> data/68529_DE-AT-CH_20261130-0443.jsonl (6 credits)
node liads.mjs diff data/68529_DE-AT-CH_20261130-0412.jsonl data/68529_DE-AT-CH_20261130-0443.jsonl
0 new, 0 no longer listed, 0 changed impression range

Nothing changed in half an hour. That's expected, because impression ranges are wide buckets and a short gap rarely moves an ad into the next one. The second run still taught me something: two different cards were rate-limited this time, the retry filled them in, and both snapshots ended with the same 81 IDs. Without the retry, a card that went missing would look like an ad that stopped running. Run it weekly, or daily during a competitor's launch. Only diff snapshots taken with the same filters and a full set of pages. If you stop at page 2, every ad from page 3 onward shows up as "no longer listed". A weekly cron line looks like this:

# Mondays 06:00: snapshot HubSpot DACH, compare with the previous snapshot
0 6 * * 1 cd ~/liads && node liads.mjs pull --company-id 68529 --countries DE,AT,CH --pages 4 && node liads.mjs diff $(ls -t data/68529_DE-AT-CH_*.jsonl | head -2 | tac)

Pitfalls I hit

  • Cloudflare 403 from a server IP. Plain fetch to /ad-library/search or /ad-library/detail/<id> got a block page, not HTML with ads in it.
  • No EU targeting means no numbers. Impressions, dates, country split and targeting only exist for ads targeted at the EU. Check impressions !== null before you average anything.
  • Ranges with an open top end. "> 1M" has no upper bound. The script counts it at 1M and prints the total as 11.2M-18M+.
  • Hair spaces in labels. "<\u200a1k" and "<\u200a1%". Strip \u200a, \u2009 and \u00a0 before parsing.
  • Shares over 100%. "100%" + "< 1%" + "< 1%"... Rescale per ad.
  • City names are ambiguous. One Salesforce Spotlight ad targeted a long list of European cities, including "Barcelona-Puerto La Cruz Metropolitan Area". That one is in Venezuela, and Venezuela duly appears in the ad's country split. Check location lists for look-alike names before you blame "spillover".
  • totalAds comes from the first page only. Later pages return null, and filtered counts don't add up. company=HubSpot&countries=DE reported 91 ads, 82 with minImpressions=100000&maxImpressions=1000000, and 45 with 1000-5000. I couldn't work out how those counts relate, so treat them as hints, not totals.
  • minImpressions alone is rejected (invalid_request). Send it together with maxImpressions.
  • Deep pages can fail. Page 4 returned 502 unsupported_page on both companies. Catch per page, and read the tail oldest-first.
  • Seven Salesforce ads that matched DE,AT,CH still had no impression data. All seven were document ads (Notion's EU document ads did have data, so the format isn't the cause). Don't assume every match is EU-targeted. Count them separately rather than as zero.

Wrapping up

  • The useful part of the LinkedIn Ad Library is the EU data. Impression ranges, per-country splits and targeting flags turn "they run ads" into "they put ~80% of a 10M+ impression budget into Germany, in two languages".
  • Parse ranges as ranges. Keep lo/hi, rescale country shares, and label every total as an estimate.
  • Filter on companyId, and separate always-on ads from campaigns before comparing competitors.
  • LinkedIn's terms ban scraping. Read them, prefer the official Ad Library API if you can get access, keep volumes small, and leave individual people out of it.

*I build it.

來源:DEV Community · dev.to