DEV Community

Bachir Djoukbala
Bachir Djoukbala

Posted on

How to scrape the LinkedIn Ad Library for competitor ads (Python, no login)

LinkedIn's Ad Library is public: you can see which ads a company or keyword is running without logging in. That makes it useful for competitor research and B2B lead lists (companies that advertise a product are companies with budget). Here is a minimal Python version that searches by keyword and country and reads each ad's detail page.

import re, html, httpx
H = {"User-Agent": "Mozilla/5.0"}
def ads(keyword, country="", limit=5):
    r = httpx.get("https://www.linkedin.com/ad-library/search",
                  params={"keyword": keyword, "countries": country}, headers=H, timeout=30, follow_redirects=True)
    ids = list(dict.fromkeys(re.findall(r"ad-library/detail/(\d+)", r.text)))[:limit]
    for i in ids:
        d = httpx.get(f"https://www.linkedin.com/ad-library/detail/{i}", headers=H, timeout=30, follow_redirects=True).text
        h = [re.sub(r"\s+", " ", html.unescape(x)).strip() for x in re.findall(r"<h\d[^>]*>(.*?)</h\d>", d, re.S)]
        title = next((x for x in h if x not in ("Ad Details", "About the ad", "Ad Impressions", "Ad Targeting")), "")
        print(i, "|", title)
ads("crm", "DE", 3)
Enter fullscreen mode Exit fullscreen mode

Output is an ad ID and a best-effort headline per line (the heading order varies between ad formats, so real parsing needs per-format handling). Each detail page also lists the advertiser, impressions range and targeting, which you can parse from the same HTML.

Be polite: keep concurrency low (2 or so), back off when you get a 429, and paginate through /ad-library/searchPaginationFragment?paginationToken=... for more than the first page.

If you would rather not maintain the parsing, pagination and retries, I built an Apify actor that does it (disclosure: it is mine): LinkedIn Ad Library Scraper, pay per ad, about $0.0008 per ad including full details. https://apify.com/rejoicing_shanty/linkedin-ad-library-scraper

Questions or missing fields? Leave a comment and I will look.

Top comments (0)