Back to use cases

    Use case / SOCIAL DATA / Python 3 / Published

    Track Competitor Ads in the Facebook Ad Library with Python

    Pull public Facebook ad library records with Python. Group ads by angle and offer, save snapshots, and review changes against an earlier run.

    Card for Track Competitor Ads in the Facebook Ad Library with Python

    Ad Library Angle Log is a small Python script for e-commerce marketers. Give it one or more store names and it pulls matching public records from the Facebook Ad Library, then writes an angle log per store: which hooks, offers and themes the store is running, and how long each ad has been live.

    The problem

    The Facebook Ad Library is public, but reading it by hand is slow. Each version of a creative shows up as its own ad, offers are buried in the copy, and there is no easy way to see what changed since last week. Marketers who watch a few competitors need a short, repeatable summary instead of scrolling.

    What the app does

    • Takes one or more store or brand names.
    • Pulls matching Ad Library records: ad copy, start date, advertiser page and media.
    • Separates ads from the store itself from ads by other advertisers that mention it.
    • Groups identical copies and tags angles such as offer, new arrival, motivation, comfort, community, seasonal and social proof.
    • Pulls offers from the copy, such as percent off, codes and free shipping.
    • Saves a snapshot and writes a diff against an earlier run: new ads, ads that stopped, ads unchanged.

    How it works

    1. Probe. A count: 1 call to POST /desearch/facebook/search checks the keyword matches anything, so an empty keyword costs nothing more.
    2. Search. A second call with count: 30 returns up to 30 ad records with copy, start time and advertiser.
    3. Normalize and group. Start dates become "days since start". Ads with identical copy are grouped as versions of one creative.
    4. Tag angles. Keyword rules (English plus several European languages) tag each copy with angles and offers.
    5. Optional landing pages. When an ad names a URL, GET /web/extract reads that page as text.
    6. Write the angle log, the snapshot and, if asked, the diff.

    The code

    PYTHON
    def search_store(store: str, count: int, key: str, raw_dir: Path | None, probe: bool) -> dict:
        calls = []
        s = slug(store)
        if probe and count > 1:
            # Probe first. Empty results cost $0, and count=1 skips a full search when the keyword matches nothing.
            c = call("POST", FB_SEARCH, key, body={"query": store, "count": 1}, raw_dir=raw_dir, raw_name=f"{s}-probe-count1.json")
            calls.append({"purpose": "probe", "requested": 1, **{k: c[k] for k in ("status", "latency_s", "cost")},
                          "returned": len(c["body"]) if isinstance(c["body"], list) else None})
            if c["status"] != 200 or not isinstance(c["body"], list) or not c["body"]:
                return {"calls": calls, "raw_ads": [], "note": "probe returned no ads, full search skipped"}
        c = call("POST", FB_SEARCH, key, body={"query": store, "count": count}, raw_dir=raw_dir, raw_name=f"{s}-search-count{count}.json")
        ads = c["body"] if isinstance(c["body"], list) else []
        calls.append({"purpose": "search", "requested": count, **{k: c[k] for k in ("status", "latency_s", "cost")},
                      "returned": len(ads) if isinstance(c["body"], list) else None,
                      "error_body": None if isinstance(c["body"], list) else c["body"]})
        return {"calls": calls, "raw_ads": ads, "note": None}
    
    
    def extract_landing(url: str, key: str, raw_dir: Path | None, idx: int) -> dict:
        u = url if url.startswith("http") else "https://" + url
        c = call("GET", EXTRACT, key, params={"url": u, "format": "text"}, raw_dir=raw_dir, raw_name=f"extract-{idx:02d}.json")
        # Only a 200 body is page text. An empty page is HTTP 404 "No content found" and is not billed.
        if c["status"] == 200:
            text = c["body"] if isinstance(c["body"], str) else json.dumps(c["body"])[:2000]
        else:
            text = ""
        return {"url": u, "status": c["status"], "cost": c["cost"], "chars": len(text or ""),
                "offers_on_page": find_all(OFFER_PATTERNS, text or "")[:8], "excerpt": (text or "")[:400]}

    The folder has one script, adlog.py (commands run, diff and render), an offline test for the diff logic in test_diff.py, and a full sample in sample-output.md.

    Endpoints

    • POST /desearch/facebook/search
    • GET /web/extract

    Example output

    From a live run on 2026-10-05 for one sportswear store, count: 30:

    MeasureValue
    Ads returned30 (24 from the store, 6 from other advertisers)
    Distinct ad copies from the store10
    Ads tagged "offer / discount"17 (4 distinct copies)
    Ads tagged "motivation / identity"16 (3 distinct copies)
    Ads tagged "new arrival / launch"10 (3 distinct copies)

    A second run 20 minutes later showed 0 new and 0 stopped ads, which is what the diff is for: run it daily or weekly and only read the changes.

    Run it yourself

    The public examples folder linked above includes the script and a README. Install its requirements, set DESEARCH_API_KEY from console.desearch.ai, and use the run command in that README.

    Useful flags: --count (ads per store, up to 30 per request), --extract N (read up to N landing pages named in ads), --diff-against latest (compare with the newest earlier snapshot).

    What it costs

    Each ad returned cost $0.00207 on 2026-10-05, read from the X-Desearch-Cost-Usd header. One store with the defaults came to $0.064 and two stores to $0.128. A keyword with no ads costs $0. See pricing.

    Ideas to extend it

    The angle log is for marketers reviewing public ads from stores in their category. Grouped copies let them read the hooks and offers without treating every creative version as a separate message. Saved snapshots provide the earlier run used by the diff.

    • Run it weekly with cron and send only the diff to your team chat.
    • Track a whole category (5 to 10 stores) and compare which angles each one leans on.
    • Add an LLM step that rewrites the top angles as briefs for your own creative team.

    Use with AI agents

    Point an MCP client at the hosted Desearch server. Replace the placeholder with a key from the console. Do not commit the key.

    JSON
    {
      "mcpServers": {
        "desearch": {
          "url": "https://mcp.desearch.ai/mcp",
          "headers": {
            "Authorization": "Bearer <key>"
          }
        }
      }
    }

    Prompt you can paste for this example:

    Use Desearch to pull public Facebook Ad Library ads for one store I name. Group the ads by angle and offer, list the landing pages, and describe what changed if I paste an earlier run. Only use ads you actually retrieve. Do not invent ads or offers.

    Build your own example.

    Give your agents access to web and social search. Get an API key to start building, or talk to us about your integration.

    Read docs