You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Playwright批量测试中屏蔽谷歌广告?

彻底屏蔽谷歌广告的Playwright解决方案

针对你测试https://automationexercise.com/时遇到的谷歌广告干扰问题,以下是几种更可靠的方案,能从根源上避免广告加载或干扰测试:

1. 拦截广告相关网络请求(最推荐)

直接阻止广告资源的请求,从根源上避免广告加载。Playwright可以在测试上下文初始化时配置路由规则,拦截常见广告域名和资源:

const { test } = require('@playwright/test');

test.beforeEach(async ({ context }) => {
  // 拦截主流广告平台的域名请求
  await context.route(/(googleads|doubleclick|googlesyndication|adnxs|adservice|advertising)/, route => route.abort());
  
  // 额外拦截包含广告关键词的资源文件(脚本、图片、样式等)
  await context.route('**/*.{js,css,png,jpg,gif,html}', route => {
    const url = route.request().url();
    if (url.includes('ad') || url.includes('advert')) {
      route.abort();
    } else {
      route.continue();
    }
  });
});

这种方法的优势是广告根本不会被加载,完全避免了广告弹窗或元素干扰测试的问题,且不受广告iframe命名变化的影响(比如你之前遇到的aswift_2可能动态变更的情况)。

2. 注入脚本屏蔽广告加载逻辑

通过content script注入页面,覆盖或阻止广告相关的全局函数和DOM操作,防止广告动态插入:

test.beforeEach(async ({ browser }) => {
  const context = await browser.newContext({
    contentScripts: [{
      content: `
        // 覆盖谷歌广告的全局变量,阻止初始化
        window.google_ad_client = '';
        window.googletag = { cmd: [], display: () => {} };
        
        // 拦截广告iframe的插入操作
        const originalAppend = Element.prototype.appendChild;
        Element.prototype.appendChild = function(node) {
          if (node.tagName === 'IFRAME' && (node.src?.includes('ad') || node.name?.includes('ad'))) {
            return null;
          }
          return originalAppend.call(this, node);
        };

        // 拦截广告容器的创建
        const originalCreateElement = document.createElement;
        document.createElement = function(tag) {
          const elem = originalCreateElement.call(this, tag);
          if (tag === 'div' && elem.className?.includes('ad')) {
            elem.style.display = 'none';
          }
          return elem;
        };
      `,
      matches: ['https://automationexercise.com/**']
    }]
  });
});

3. 兜底:强制隐藏广告元素

如果前两种方法有漏网的广告,可以通过注入CSS强制隐藏所有广告相关元素:

test.beforeEach(async ({ page }) => {
  await page.addStyleTag({
    content: `
      /* 隐藏所有广告相关iframe */
      iframe[name*="ad"], iframe[name*="swift"], iframe[src*="ad"] {
        display: none !important;
        visibility: hidden !important;
        position: absolute !important;
        top: -9999px !important;
      }
      /* 隐藏页面内的广告容器 */
      [class*="ad"], [id*="ad"], [data-ad] {
        display: none !important;
      }
    `
  });
});

为什么你之前的方法失效?

  • 点击关闭按钮的方法:广告iframe的name属性(如aswift_2)可能会动态变化,导致定位器失效;且部分广告可能没有关闭按钮。
  • goBack()/goForward()的方法:批量测试时,每个测试的页面上下文是独立的(或状态重置),广告会重新加载,且依赖页面导航逻辑,稳定性差。

建议组合使用网络请求拦截+兜底CSS隐藏,基本可以彻底解决广告干扰问题。

内容的提问来源于stack exchange,提问作者Adam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:33:31