Ad networks leave fingerprints in the DOM. Google Ad Manager loads iframes from securepubads.g.doubleclick.net. Taboola injects divs with tbl-feed class names. Amazon publisher ads pull scripts from aax.amazon-adsystem.com. If you can read the rendered page structure, you can map every ad on it - which network serves it, where it sits, how much viewport space it takes. The Page Analysis API does exactly that: one POST request returns every element on a rendered page as structured JSON, each with a bounding rectangle in pixels.
But ad detection on the real web is trickier than matching a few domain names. Google Ad Manager serves through securepubads.g.doubleclick.net, but it also loads through custom CNAME records that look like first-party domains. Amazon publisher ads come through aax.amazon-adsystem.com on some sites and through CloudFront CDN URLs on others. Native advertising platforms like Taboola and Outbrain inject recommendation widgets that look like editorial content until you inspect the DOM. Sticky footer ads with 1x1 tracking pixels sit outside the viewport but fire dozens of network requests. And sites running header bidding through Prebid.js negotiate with 15-20 demand partners before a single ad renders, all happening in JavaScript after page load.
This post walks through how to detect ads on any URL programmatically, classify them by ad network, map their viewport positions, measure their density, use the results to make decisions - whether that means blocking them in screenshots, auditing a publisher's ad setup, or verifying that ads display correctly across devices.
Why detect ads instead of just blocking them?
ScreenshotRun already has a block_ads parameter that removes advertisements from screenshots. Set block_ads=true and the capture comes back clean. But blocking and detecting serve different purposes.
Blocking is a capture-time decision: you want a clean screenshot, so you remove ads before the render. Detection is an analysis task: you want to know what ads a page has, where they sit, which networks serve them, how much viewport space they consume. You need detection when:
- Ad verification teams audit whether placements render correctly on a publisher's site
- Publishers check that ad slots load across different geolocations and devices
- SEO teams measure ad density against Google's mobile interstitial guidelines
- Competitive intelligence scripts track which ad networks a competitor uses
- Compliance teams verify that regulated industries (pharma, finance, alcohol) display required disclaimers alongside their ads
- Brand safety audits check what content appears next to a brand's ad placements
In each case, the goal is not to remove ads but to understand them. (For detecting popups and overlays instead of ads, see our popup detection guide.)
Detecting ads with the Page Analysis endpoint
The /v1/analyze endpoint renders the page in a real browser, executes all JavaScript (including ad auction scripts), and returns structured data about every element. To find ads, request the interactive and images categories - ad units show up as iframes, images, clickable elements, all sourced from advertising domains.
curl -X POST https://api.screenshotrun.com/v1/analyze \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"url": "https://news-site.example.com/article/tech-review",
"include": ["interactive", "images", "text"],
"delay": 3
}'
Adding delay: 3 gives ad scripts three seconds to complete their auction and render. Without it, you might catch the page before header bidding finishes and ads populate their slots. For sites running Prebid.js or Amazon TAM, three seconds is usually enough. Heavy ad setups on news sites might need five.
Filtering the response for ad elements
Every element on the page comes back in the response. To isolate ads, filter by known patterns. Here is a Python script that processes the response and identifies ad-related elements:
import httpx, json, re
API_KEY = "YOUR_API_KEY"
resp = httpx.post(
"https://api.screenshotrun.com/v1/analyze",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"url": "https://news-site.example.com/article/tech-review",
"include": ["interactive", "images"],
"delay": 3,
},
timeout=30,
)
data = resp.json()
# Known ad network domains
AD_DOMAINS = [
"doubleclick.net", "googlesyndication.com", "googleadservices.com",
"google-analytics.com/ads", "adnxs.com", "amazon-adsystem.com",
"taboola.com", "outbrain.com", "criteo.com", "media.net",
"pubmatic.com", "rubiconproject.com", "openx.net", "adsrvr.org",
"moatads.com", "serving-sys.com", "carbonads.com",
]
# Common ad-related CSS patterns
AD_PATTERNS = re.compile(
r"(^ad[-_]|[-_]ad[-_]|[-_]ad$|^ads[-_]|[-_]ads[-_]|"
r"advert|banner[-_]ad|google[-_]ad|sponsor|dfp[-_]|"
r"gpt[-_]slot|ad[-_]unit|ad[-_]slot|ad[-_]wrapper|"
r"ad[-_]container|leaderboard|skyscraper|mpu[-_])",
re.IGNORECASE,
)
ad_elements = []
for category in ["interactive", "images"]:
for el in data.get(category, []):
src = el.get("src", "") or el.get("href", "") or ""
class_name = el.get("class", "")
el_id = el.get("id", "")
is_ad = False
reason = []
# Check source URL against ad domains
for domain in AD_DOMAINS:
if domain in src:
is_ad = True
reason.append(f"domain:{domain}")
break
# Check class/ID against ad patterns
if AD_PATTERNS.search(class_name):
is_ad = True
reason.append(f"class:{class_name}")
if AD_PATTERNS.search(el_id):
is_ad = True
reason.append(f"id:{el_id}")
if is_ad:
ad_elements.append({
"tag": el.get("tag"),
"rect": el.get("rect"),
"reason": reason,
"src": src[:120],
})
print(f"Found {len(ad_elements)} ad elements")
for ad in ad_elements:
r = ad["rect"]
area = r[2] * r[3] if r else 0
print(f" {ad['tag']} at ({r[0]},{r[1]}) {r[2]}x{r[3]}px "
f"({area:,}px²) — {', '.join(ad['reason'])}")
This script catches the obvious cases: Google Ad Manager iframes, Amazon display ads, Taboola widgets, Criteo retargeting blocks. The regex patterns match common ad container naming conventions that most publishers and CMS platforms use.
Measuring ad density and viewport coverage
Google penalizes mobile pages where ads occupy too much of the initial viewport. Their internal metric adsDensityInterstitialViolationStrength fires when ad content exceeds roughly 30% of the visible area above the fold. To measure this programmatically, calculate the viewport coverage from the bounding rectangles:
VIEWPORT_WIDTH = 390 # iPhone 14 Pro
VIEWPORT_HEIGHT = 844
def viewport_overlap(rect, vw=VIEWPORT_WIDTH, vh=VIEWPORT_HEIGHT):
"""Calculate how much of an element overlaps the initial viewport."""
x, y, w, h = rect
overlap_x = max(0, min(x + w, vw) - max(x, 0))
overlap_y = max(0, min(y + h, vh) - max(y, 0))
return overlap_x * overlap_y
total_ad_area = 0
viewport_area = VIEWPORT_WIDTH * VIEWPORT_HEIGHT
for ad in ad_elements:
if ad["rect"]:
overlap = viewport_overlap(ad["rect"])
total_ad_area += overlap
density = total_ad_area / viewport_area * 100
print(f"Ad density in viewport: {density:.1f}%")
if density > 30:
print("WARNING: Exceeds Google's mobile ad density threshold")
Run this across a batch of URLs and you get an ad density audit for an entire site. SEO agencies use this pattern to identify pages that might trigger Google's mobile interstitial penalty before they lose rankings.
Detecting specific ad networks
Sometimes you need more than "this page has ads." Ad verification companies need to confirm that a specific campaign renders on a specific publisher page. Media buyers need to verify that their programmatic buys actually appear. Here is how to check for specific networks:
NETWORK_SIGNATURES = {
"Google Ad Manager": ["securepubads.g.doubleclick.net", "googletag.pubads"],
"Google AdSense": ["pagead2.googlesyndication.com", "adsbygoogle"],
"Amazon Publisher Services": ["aax.amazon-adsystem.com", "amzn_assoc"],
"Taboola": ["cdn.taboola.com", "tbl-feed", "taboola-below"],
"Outbrain": ["outbrain.com/widget", "ob-widget"],
"Criteo": ["static.criteo.net", "crt-"],
"Media.net": ["contextual.media.net"],
"Carbon Ads": ["carbonads.com", "carbon-ad"],
}
detected_networks = set()
for category in ["interactive", "images"]:
for el in data.get(category, []):
src = el.get("src", "") or ""
class_name = el.get("class", "") + " " + el.get("id", "")
for network, signatures in NETWORK_SIGNATURES.items():
for sig in signatures:
if sig in src or sig in class_name:
detected_networks.add(network)
print("Ad networks detected:")
for net in sorted(detected_networks):
print(f" - {net}")
This approach catches the major display advertising platforms. It will not detect server-side ad insertion (SSAI) used by video streaming platforms, or ads injected through service workers - those operate at a layer below the DOM.
Combining detection with screenshots
Detection tells you what ads exist. The next step is usually visual: capture the page both with and without ads to compare. Use the regular ad blocking parameter for the clean version, and a standard capture for the ad-included version.
import httpx
API_KEY = "YOUR_API_KEY"
BASE = "https://api.screenshotrun.com/v1/screenshots/capture"
url = "https://news-site.example.com/article/tech-review"
# Capture WITH ads
resp_with = httpx.get(BASE, params={
"url": url,
"format": "png",
"full_page": "true",
"device": "mobile",
"block_cookies": "true",
}, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30)
with open("with-ads.png", "wb") as f:
f.write(resp_with.content)
# Capture WITHOUT ads
resp_without = httpx.get(BASE, params={
"url": url,
"format": "png",
"full_page": "true",
"device": "mobile",
"block_cookies": "true",
"block_ads": "true",
}, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30)
with open("without-ads.png", "wb") as f:
f.write(resp_without.content)
Comparing the two captures shows exactly what the ads contribute visually. For ad verification, overlay the detected bounding rectangles onto the screenshot to highlight where each ad unit renders. For page speed audits, the size difference between the two captures gives a rough measure of ad-related page weight.
Edge cases that break simple detection
Domain matching paired with class-name checks works for 80-90% of ads. The remaining cases require more context:
CNAME cloaking. Some publishers proxy ad requests through their own domain using CNAME DNS records. What looks like ads.publisher.com actually resolves to securepubads.g.doubleclick.net. The Page Analysis API sees the publisher's domain in the src attribute, not the ad network. Detecting these requires DNS resolution or checking the response headers - which the API does not do.
Native advertising widgets. Taboola and Outbrain recommendation blocks often use class names like recommendation-widget or sponsored-content rather than obvious ad identifiers. The domain check catches them when they load from cdn.taboola.com, but server-rendered native ads that load from the publisher's own CMS look identical to editorial content in the DOM.
Lazy-loaded ad slots. Many publishers defer ad loading until the user scrolls to that section. If you analyze only the initial page state, you miss below-fold ads entirely. Increase the delay parameter or use full-page mode which triggers a scroll before analysis, forcing lazy ad slots to initialize.
Consent-gated ads. In GDPR jurisdictions, ads do not load until the user accepts the cookie consent banner. If block_cookies=true dismisses the banner but the page interprets that as "rejected," no personalized ads load. For accurate ad detection in the EU, you may need to inject consent via the JavaScript injection parameter to simulate acceptance.
Batch auditing across a site
Single-page detection is a starting point. For publishers managing hundreds of pages, run the analysis in a batch to build an ad inventory map across the entire site:
import httpx, json, csv
API_KEY = "YOUR_API_KEY"
urls = json.load(open("sitemap-urls.json"))
results = []
for url in urls:
try:
resp = httpx.post(
"https://api.screenshotrun.com/v1/analyze",
headers={"Authorization": f"Bearer {API_KEY}"},
json={"url": url, "include": ["interactive", "images"], "delay": 3},
timeout=30,
)
data = resp.json()
ad_count = count_ad_elements(data) # reuse function from earlier
density = calculate_ad_density(data)
networks = detect_networks(data)
results.append({
"url": url,
"ad_count": ad_count,
"density_pct": round(density, 1),
"networks": ", ".join(networks),
})
except Exception as e:
results.append({"url": url, "ad_count": -1, "density_pct": -1, "networks": str(e)})
with open("ad-audit.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["url", "ad_count", "density_pct", "networks"])
writer.writeheader()
writer.writerows(results)
print(f"Audited {len(results)} pages → ad-audit.csv")
That CSV gives you a per-page breakdown: how many ad elements, what percentage of the viewport they cover, which networks serve them. Sort by density to find the most ad-heavy pages. Filter by network to see where a specific ad partner runs.
What the API catches and what it misses
Page Analysis renders JavaScript, so it detects ads that load dynamically through ad servers, header bidding, client-side auction scripts, real-time exchange calls. It sees the final rendered DOM after all scripts execute - which is what matters for visual ad detection.
It does not detect: server-side ad insertion (common in video streaming), ads loaded only after user interaction (click-triggered popunders), ads behind A/B testing frameworks that only serve to certain audience segments, or tracking pixels that have no visual footprint. For full-scope ad verification beyond visual detection, dedicated tools like DoubleVerify, IAS, or MOAT provide deeper instrumentation including viewability metrics, brand safety scoring, and fraud detection.
For the 90% of ad detection tasks that involve knowing what ads appear on a page, where they sit, which networks deliver them, how much screen real estate they consume - the API combined with the filtering approach above handles it in a few lines of code. At two hundred free captures per month on the free plan, you can audit a small publisher's entire site without spending anything.
FAQ#
The Page Analysis API detects ads that render in the DOM - display ads from Google Ad Manager, AdSense, Amazon, Taboola, Outbrain, Criteo, Media.net, Carbon Ads, and other networks that load through JavaScript. It does not detect server-side ad insertion (SSAI) used in video streaming, ads behind A/B testing that only serve to certain segments, or tracking pixels with no visual footprint.
Domain matching combined with CSS class/ID pattern detection catches 80-90% of display ads. The main gaps are CNAME-cloaked ads (where publishers proxy ad requests through their own domain), server-rendered native advertising that uses no ad-network identifiers, and ads loaded only after user interaction. For most auditing tasks - ad density measurement, network identification, placement verification - the detection is reliable enough to act on.
Modern ad setups use header bidding (Prebid.js, Amazon TAM) which runs a client-side auction among multiple demand partners before ads render. This auction takes 1-3 seconds after page load. Without a delay, you might analyze the page before ads populate their slots. A delay of 3 seconds works for most sites. Heavy ad setups on news sites might need 5 seconds.
Google penalizes mobile pages where ads exceed roughly 30% of the initial viewport. Use the Page Analysis API to get bounding rectangles for all ad elements, calculate their overlap with the viewport area (390x844 for iPhone 14 Pro), and sum the percentages. Run this across all pages on a site to identify which ones risk triggering the mobile interstitial penalty.
In GDPR jurisdictions, personalized ads do not load until the user accepts the consent banner. If block_cookies=true dismisses the banner but the page interprets it as rejection, no ads appear. For accurate ad detection in the EU, use the JavaScript injection parameter to simulate consent acceptance before analysis.