Selenium自动化测试中屏蔽网页内嵌广告的解决方案求助
问题描述
我正在用Selenium完成质量保证自动化方向的学术作业,测试对象是一个非本人及熟人维护的网站。运行测试用例时,Chrome窗口内的网站偶尔会出现内嵌广告——这类广告不是弹窗,所以disable-popup-blocking参数没用;而且广告不是每次都出现,写固定代码段关闭广告模态框的方案也不适用。
广告场景示例图:
以下是我的测试用例示例:
@Test @Order(2) public void CovertLang() throws InterruptedException { // 导航到123apps.com网站 driver.get("https://123apps.com/"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // 点击语言切换按钮 WebElement langButton = driver.findElement(By.id("language-link")); langButton.click(); // 等待语言选择模态框显示 wait.until(ExpectedConditions .visibilityOfElementLocated(By.className("modal-title"))); // 选择德语 WebElement deutschButton = driver.findElement(By.xpath("//a[@href='/de/']")); deutschButton.click(); Thread.sleep(1000); // 验证当前URL是否正确 String newURL = driver.getCurrentUrl(); assertEquals("https://123apps.com/de/", newURL); }
可行解决方案
1. 加载广告屏蔽扩展
给ChromeDriver配置广告屏蔽扩展(比如uBlock Origin),从根源阻止广告加载:
ChromeOptions options = new ChromeOptions(); // 加载本地的uBlock Origin扩展文件(需提前下载对应Chrome版本的.crx格式文件) options.addExtensions(new File("path/to/ublock-origin.crx")); WebDriver driver = new ChromeDriver(options);
2. 动态检测并移除广告元素
写通用检测逻辑,在关键操作前检查页面是否存在广告元素,若存在则通过JS移除:
// 封装移除广告的方法 private void removeAds(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; // 根据广告元素的特征选择器调整(可通过浏览器开发者工具获取) String[] adSelectors = { ".ad-container", "#inline-ad", "[class*='ad']" // 匹配包含ad关键词的类名 }; for (String selector : adSelectors) { try { js.executeScript("document.querySelectorAll('" + selector + "').forEach(el => el.remove());"); } catch (Exception e) { // 无广告时忽略异常 } } } // 在测试用例中调用 @Test @Order(2) public void CovertLang() throws InterruptedException { driver.get("https://123apps.com/"); // 导航后立即执行广告移除 removeAds(driver); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement langButton = driver.findElement(By.id("language-link")); langButton.click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("modal-title"))); WebElement deutschButton = driver.findElement(By.xpath("//a[@href='/de/']")); deutschButton.click(); Thread.sleep(1000); String newURL = driver.getCurrentUrl(); assertEquals("https://123apps.com/de/", newURL); }
3. 启用Chrome内置广告过滤
通过ChromeOptions添加启动参数,开启浏览器自带的广告拦截功能:
ChromeOptions options = new ChromeOptions(); options.addArguments("--enable-features=AdsDataReduction,AdPrivacyEnforcement"); WebDriver driver = new ChromeDriver(options);
内容的提问来源于stack exchange,提问作者DiWeera98
相关产品推荐
相关产品推荐

