当预期无弹窗却出现 UnexpectedAlert 时,如何自动截图并关闭?
解读
国内主流 Web 项目普遍采用 Selenium + Pytest/TestNG 做回归测试,线上环境偶发 第三方广告、会话超时、接口异常 等场景,会触发浏览器级 alert/confirm/prompt。这类弹窗不在用例预期路径内,若未处理会抛出 UnhandledAlertException,导致后续步骤全部失败,且无法还原现场。面试官希望候选人给出 “先取证、再恢复、最后记录” 的闭环方案,能在 分布式节点(Docker/Selenium Grid) 上稳定运行,并兼容 Chrome/Firefox/Edge 的驱动差异。
知识点
- WebDriverWait + expected_conditions.alert_is_present() 的 轮询机制(默认 0.5 s 频率),避免
driver.switch_to.alert硬编码造成的 NoAlertPresentException。 - Alert.text 属性可提取弹窗文本,用于日志与缺陷报告,超长文本需截断防止 IO 阻塞。
- Alert.dismiss() 与 Alert.accept() 的行为差异:前者点击“取消/关闭”,后者点击“确定”;国内很多后台系统把超时提醒做成 confirm(),必须根据业务语义选择。
- UnexpectedAlert 会 阻塞页面 DOM,导致截图时 视口空白;需先切换回 default_content 再执行
save_screenshot(),否则只能截到弹窗本身。 - Pytest 插件钩子 pytest_exception_interact 或 TestNG IInvokedMethodListener,可在 全局捕获 UnhandledAlertException,实现 一次配置、全用例生效,避免重复 try-catch。
- 多线程/Grid 模式下,截图文件名必须包含 节点 IP、线程号、时间戳,防止并发覆盖;推荐使用 UUID + 用例方法名 拼接。
- 日志规范:截图路径需打印到 Slf4j/Logback 或 logging 的 error 级别,并与 Allure/ReportPortal 等报告平台 附件接口 对接,方便 CI 侧直接归档。
- 浏览器驱动差异:Chrome 90+ 之后,--disable-popup-blocking 不再抑制 alert,需通过 DevTools Command
Page.addScriptToEvaluateOnNewDocument注入window.alert = function(){};才能 彻底屏蔽(但会干扰业务弹窗,慎用)。
答案
下面给出 基于 Pytest + Selenium 4(Python 绑定) 的 生产级示例,可直接放入 conftest.py,实现 “出现意外弹窗→自动截图→关闭弹窗→继续运行” 的完整闭环。
import uuid, os, logging, datetime
from selenium.common.exceptions import UnexpectedAlertPresentException, WebDriverException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def _handle_unexpected_alert(driver, case_name):
"""
统一处理 UnexpectedAlert:截图 + 日志 + 关闭
"""
try:
alert = WebDriverWait(driver, 2).until(EC.alert_is_present())
alert_text = alert.text[:200] # 防止文本过长
logging.error("【UnexpectedAlert】用例 %s 出现意外弹窗,文本:%s", case_name, alert_text)
# 1. 截图:文件名含时间+线程+UUID
timestamp = datetime.datetime.now().strftime("%m%d-%H%M%S")
file_name = f"{case_name}_{timestamp}_{uuid.uuid4().hex[:8]}.png"
screenshot_dir = os.path.join(os.getcwd(), "screenshots")
os.makedirs(screenshot_dir, exist_ok=True)
full_path = os.path.join(screenshot_dir, file_name)
# 先切回 default_content,确保页面可见
driver.switch_to.default_content()
driver.save_screenshot(full_path)
logging.error("【UnexpectedAlert】已截图:%s", full_path)
# 2. 关闭弹窗:优先 dismiss,防止误操作
alert.dismiss()
logging.warning("【UnexpectedAlert】已调用 dismiss() 关闭弹窗")
return full_path
except Exception as e:
logging.exception("【UnexpectedAlert】关闭弹窗失败:%s", e)
return None
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""
钩子:在测试执行阶段捕获 UnexpectedAlertPresentException
"""
outcome = yield
rep = outcome.get_result()
if rep.when == "call" and rep.failed:
driver = item.funcargs.get("driver")
if driver and "UnexpectedAlertPresentException" in str(call.excinfo.value):
case_name = item.originalname or item.name
_handle_unexpected_alert(driver, case_name)
使用方式:
- 用例层 无需任何 try-catch,保持 PO 模式 纯净断言。
- 当 UnexpectedAlertPresentException 抛出,钩子自动截图并关闭弹窗,用例标记为失败但进程不中断,后续用例继续执行。
- CI 侧 通过
screenshots/*.png与日志关键字 【UnexpectedAlert】 即可快速定位现场。
拓展思考
-
如何区分“业务预期弹窗”与“意外弹窗”?
可在 PageObject 层封装 wait_alert(),内部记录 “已预期” 标志位;钩子层通过 ThreadLocal 判断,仅当标志位为 False 时才触发截图关闭逻辑,避免误杀正常流程。 -
弹窗关闭后页面 DOM 被刷新,如何恢复断点?
推荐引入 Selenium BiDi API(Chrome DevTools Protocol),监听Page.javascriptDialogOpening事件,在弹窗出现前自动保存当前 URL 与 cookie,关闭后 重新导航并恢复会话,实现 “断点续跑”。 -
国内小程序内嵌 WebView 场景,alert 由 微信内核 接管,WebDriver 无法切换。此时需 切换 Context 到 NATIVE_APP,用 UiAutomator2 点击系统弹窗,混合自动化 才能闭环。
-
合规与审计:金融、医疗项目要求 “弹窗文本必须原样留存”,此时 dismiss() 会丢失文本;应改为 先读取 text,再 accept(),并把文本写入 Kafka 审计队列,截图仅作为辅助证据。