Python Selenium自动化测试:如何关闭弹窗广告?
批量运行自动化测试时弹窗广告的解决办法
核心思路
批量运行时操作频率高,容易触发网站的广告弹窗机制,单个用例间隔长则不会。解决方向分两种:提前拦截或主动检测关闭。
具体实现方案
1. 封装通用弹窗关闭函数
在你的测试类里加一个专门处理弹窗的方法,每次操作前调用,没弹窗就跳过:
def close_ad_popup(self): try: # 替换成你广告弹窗关闭按钮的实际定位(比如XPath、CSS选择器) # 示例:找带"关闭"文字或叉号的按钮 close_btn = self.driver.find_element("xpath", "//button[contains(text(), '关闭') or @class='ad-close']") if close_btn.is_displayed(): close_btn.click() # 给弹窗消失留一点时间 self.driver.implicitly_wait(2) except: # 没找到弹窗就忽略,不影响后续测试 pass
2. 把弹窗处理嵌入测试流程
修改你的Name方法,在关键步骤前调用弹窗关闭,比如页面跳转前后:
def Name(self, TestData, ExpectedErrorMessage): driver = self.driver actions = self.actions # 操作前先清掉可能存在的广告 self.close_ad_popup() # 点击New Customer driver.find_element("xpath", "//a[normalize-space()='New Customer']").click() # 页面跳转后可能又弹出广告,再检查一次 self.close_ad_popup() # 后续原有逻辑不变 driver.find_element("xpath", "//input[@name='name']").click() actions.send_keys(TestData).perform() error_displayed = driver.find_element("xpath", "//label[@id='message']").text self.assertEqual(ExpectedErrorMessage, error_displayed)
3. 浏览器层面直接拦截广告(最省心)
用Chrome的广告屏蔽插件,比如AdBlock Plus,配置到WebDriver里,从根源上阻止广告加载:
from selenium import webdriver from selenium.webdriver.chrome.options import Options def setUp(self): chrome_options = Options() # 这里替换成你下载的AdBlock插件crx文件路径 chrome_options.add_extension('/path/to/adblock_plus.crx') self.driver = webdriver.Chrome(options=chrome_options) self.actions = webdriver.ActionChains(self.driver)
4. 优化等待逻辑,适配批量运行节奏
批量运行时页面加载快,弹窗可能还没出来就执行下一步,用显式等待确保弹窗加载完成再处理:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def close_ad_popup(self): try: # 最多等3秒找关闭按钮 close_btn = WebDriverWait(self.driver, 3).until( EC.presence_of_element_located(("xpath", "//button[contains(text(), '×')]")) ) if close_btn.is_displayed(): close_btn.click() except: pass
额外提示
- 如果广告的定位元素经常变,尽量用通用特征定位,比如找所有带"关闭"、"×"的按钮,或者弹窗容器里的第一个可点击元素
- 批量运行时别太急,可在测试用例之间加1秒左右的等待:
import time; time.sleep(1)(临时救急可用,不推荐长期依赖) - 有些网站的广告是反自动化触发的,模拟真实用户的操作速度(比如输入前停顿一下)也能减少弹窗
内容的提问来源于stack exchange,提问作者JahKeem
相关产品推荐
相关产品推荐

