如何自动识别并遮罩广告位 iframe?
解读
国内主流站点(如电商、门户、短视频平台)普遍采用异步动态注入 iframe 的方式加载广告,且为了反爬与反屏蔽,经常给 iframe 随机生成 src、id、class,甚至嵌套多层。面试时,面试官想考察三点:
- 能否在不固定属性的情况下,用多维度特征稳定定位广告 iframe;
- 定位后如何安全遮罩(不影响页面布局、不触发广告监测脚本、不违反同源策略);
- 方案是否具备工程化落地能力(可配置、可回滚、可灰度、可上报)。
一句话:不是简单地把元素 hide 掉,而是“智能识别 + 零侵入遮罩 + 可观测性”。
知识点
- 动态特征识别:基于
src正则、宽高比、可见性、跨域属性sandbox、子节点img尺寸、CSS 背景图域名黑名单等加权打分。 - Shadow DOM 穿透:国内部分广告采用
shadow-root封装,需通过driver.execute_script('return arguments[0].shadowRoot')递归查找。 - 跨域限制:iframe 与主页面不同源时,无法直接操作其内部 DOM,只能对 iframe 本身做遮罩。
- 零侵入遮罩:使用
position:fixed的半透明遮罩层覆盖 iframe 坐标,而非修改 iframe 的display或visibility,避免触发广告方的visibilitychange监测。 - 性能与稳定性:利用
WebDriverWait+staleness_of等待 iframe 完全加载,再执行遮罩;通过MutationObserver监听后续动态插入,实现热更新。 - 合规上报:记录遮罩次数、广告位 ID、页面 URL,通过
Image beacon回传日志,满足国内广告法“可验证屏蔽”要求。
答案
给出一套可直接落地的 Python 伪代码,演示核心思路:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re, json, time
def is_ad_iframe(iframe):
"""多维度打分识别广告 iframe,返回布尔值"""
score = 0
src = iframe.get_attribute("src") or ""
w = int(iframe.size["width"])
h = int(iframe.size["height"])
# 1. src 命中国内常见广告域名
if re.search(r"(doubleclick|googlesyndication|tanx|alicdn|bdstatic|gdt\\.qq)\\.com", src):
score += 40
# 2. 宽高符合国内标准广告尺寸
if (w, h) in {(300, 250), (336, 280), (728, 90), (960, 90), (1200, 90)}:
score += 30
# 3. 跨域且 sandbox 无 allow-scripts
if "sandbox" in iframe.get_attribute("outerHTML") and "allow-scripts" not in iframe.get_attribute("sandbox"):
score += 20
# 4. 可见性
if iframe.is_displayed():
score += 10
return score >= 60
def mask_iframe(driver, iframe):
"""零侵入遮罩:在主页面注入遮罩层"""
script = """
var mask = document.createElement('div');
mask.style.cssText = 'position:fixed;background:rgba(0,0,0,0.5);z-index:999999;pointer-events:none;';
var rect = arguments[0].getBoundingClientRect();
mask.style.left = (rect.left + window.scrollX) + 'px';
mask.style.top = (rect.top + window.scrollY) + 'px';
mask.style.width = rect.width + 'px';
mask.style.height = rect.height + 'px';
mask.setAttribute('data-automask','true');
document.body.appendChild(mask);
return mask;
"""
driver.execute_script(script, iframe)
def scan_and_mask(driver):
"""主流程:等待所有 iframe 加载完成,识别并遮罩"""
wait = WebDriverWait(driver, 15)
wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, "iframe")))
iframes = driver.find_elements(By.TAG_NAME, "iframe")
for f in iframes:
try:
if is_ad_iframe(f):
mask_iframe(driver, f)
# 合规上报
driver.execute_script("""
(new Image()).src='https://log.mycompany.cn/admask?url='+encodeURIComponent(location.href);
""")
except Exception:
continue
# 启动
options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled") # 反爬
driver = webdriver.Chrome(options=options)
driver.get("https://www.example-mall.cn")
scan_and_mask(driver)
# 持续监听动态插入(简化版)
driver.execute_script("""
const observer = new MutationObserver(() => {
window.dispatchEvent(new CustomEvent('scanAgain'));
});
observer.observe(document.body, {childList:true, subtree:true});
""")
driver.execute_script("""
window.addEventListener('scanAgain', () => {
// 触发 Python 端重新扫描,可通过 Chrome DevTools Protocol 或轮询实现
});
""")
关键点
- 识别逻辑可配置化:把
score阈值、域名正则、尺寸白名单放到配置中心(Nacos、Apollo),热更新无需发版。 - 遮罩层使用
pointer-events:none,保证页面可正常点击,不影响业务埋点。 - 若广告 iframe 嵌套在Shadow DOM,需递归
shadowRoot.querySelectorAll('iframe')。 - 在** Jenkins 流水线**中,可将遮罩成功率作为质量门禁,低于 98% 则拦截上线。
拓展思考
- AI 增强识别:用轻量级 CNN 对 iframe 截图做二分类(广告/非广告),结合传统规则做混合决策,准确率可从 92% 提升到 98%,但需考虑GPU 推理耗时与线上成本。
- 合规风险:国内《互联网广告管理办法》要求“一键关闭”而非简单遮罩,若客户要求可点击关闭,需在遮罩层中央增加“关闭”按钮,点击后移除遮罩并记录用户行为,避免被市场监管认定为“恶意屏蔽”。
- 小程序 WebView 场景:微信、支付宝小程序内嵌 H5 页面时,WebView 禁止操作跨域 iframe,此时只能把遮罩逻辑下沉到原生层(iOS 用 WKUserScript,Android 注入 JSBridge),Selenium 仅做端到端验证。
- 性能极限:页面 iframe 数量可能超过 200 个(如央视网直播页),需先用
request/response interceptor在网络层过滤广告域名,减少 DOM 扫描范围,实现毫秒级遮罩。