Selenium Java执行alert.accept()报Not attached to an active page错误求助
解决Selenium中
alert.accept()触发"Not attached to an active page"错误的方案 问题背景
通过LAN访问本地服务器网站,使用Selenium Java代码实现登录操作时,执行alert.accept()触发以下错误:
WARNING: Unable to find an exact match for CDP version 123, returning the closest version; found: 122; Please update to a Selenium version that supports CDP version 123 Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: unhandled inspector error: {"code":-32000,"message":"Not attached to an active page"} (Session info: chrome=123.0.6312.58) Build info: version: '4.18.1', revision: 'b1d3319b48' System info: os.name: 'Windows 11', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.6' Driver info: org.openqa.selenium.chrome.ChromeDriver Command: [dfac2cd703b05551ae6f7883aac610a4, acceptAlert {}] Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 123.0.6312.58, chrome: {chromedriverVersion: 123.0.6312.58 (6b4b19e9dfbb..., userDataDir: C:\Users\asaph\AppData\Loca...}, fedcm:accounts: true, goog:chromeOptions: {debuggerAddress: localhost:50271}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: windows, proxy: Proxy(), se:cdp: ws://localhost:50271/devtoo..., se:cdpVersion: 123.0.6312.58, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:extension:minPinLength: true, webauthn:extension:prf: true, webauthn:virtualAuthenticators: true} Session ID: dfac2cd703b05551ae6f7883aac610a4 at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) at org.openqa.selenium.remote.ErrorCodec.decode(ErrorCodec.java:167) at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:138) at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:50) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:190) at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:216) at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:174) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:519) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:592) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:596) at org.openqa.selenium.remote.RemoteWebDriver$RemoteAlert.accept(RemoteWebDriver.java:1180) at swagger.swapnil.Selenium.main(Selenium.java:44)
已尝试切换框架、添加超时,无法降级Chrome/Chromedriver,CDP版本警告可忽略,接受alert后本该跳转页面但报错中断。
原登录代码:
public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\xyz"); ChromeOptions options = new ChromeOptions(); options.setBinary("C:\\zyx"); WebDriver driver = new ChromeDriver(options); driver.manage().window().maximize(); driver.get("localserver:9091/"); Duration timeoutDuration = Duration.ofSeconds(5); WebDriverWait wait = new WebDriverWait(driver, timeoutDuration); WebElement usernameInput = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("userNameLi"))); WebElement passwordInput = driver.findElement(By.id("userPasswordLi")); usernameInput.sendKeys("001"); passwordInput.sendKeys("t01"); WebElement loginButton = driver.findElement(By.xpath("/html/body/table/tbody/tr/td[2]/center/div/form/button")); loginButton.click(); wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); wait.until(ExpectedConditions.alertIsPresent()); alert.accept(); }
解决方案
1. 优化Alert等待逻辑
重复调用wait.until(ExpectedConditions.alertIsPresent())会导致会话与页面状态脱节,直接等待并获取Alert实例后执行操作即可:
// 等待Alert出现并直接获取实例 Alert alert = wait.until(ExpectedConditions.alertIsPresent()); alert.accept();
2. 新增页面跳转等待
接受Alert后页面会立即跳转,需等待新页面加载完成,避免会话失联:
alert.accept(); // 等待新页面的标志性元素(替换为目标页面实际元素ID) wait.until(ExpectedConditions.presenceOfElementLocated(By.id("target-page-element-id"))); // 或等待URL变化 wait.until(ExpectedConditions.urlContains("/dashboard"));
3. 调整页面加载策略
将Chrome页面加载策略改为EAGER,减少等待页面完全加载的时间,避免会话超时:
ChromeOptions options = new ChromeOptions(); options.setBinary("C:\\zyx"); // 设置加载策略为EAGER options.setPageLoadStrategy(PageLoadStrategy.EAGER); WebDriver driver = new ChromeDriver(options);
4. 替换绝对XPath定位
原代码使用绝对XPath定位登录按钮,页面结构变化会导致定位失效,改用相对定位:
// 使用CSS选择器定位登录按钮(更稳定) WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("form button[type='submit']"))); loginButton.click();
完整修正代码
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import org.openqa.selenium.PageLoadStrategy; public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\xyz"); ChromeOptions options = new ChromeOptions(); options.setBinary("C:\\zyx"); options.setPageLoadStrategy(PageLoadStrategy.EAGER); WebDriver driver = new ChromeDriver(options); driver.manage().window().maximize(); driver.get("localserver:9091/"); Duration timeoutDuration = Duration.ofSeconds(10); WebDriverWait wait = new WebDriverWait(driver, timeoutDuration); // 等待输入框可见再操作 WebElement usernameInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("userNameLi"))); WebElement passwordInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("userPasswordLi"))); usernameInput.sendKeys("001"); passwordInput.sendKeys("t01"); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("form button"))); loginButton.click(); Alert alert = wait.until(ExpectedConditions.alertIsPresent()); alert.accept(); // 等待新页面加载完成 wait.until(ExpectedConditions.presenceOfElementLocated(By.id("target-page-element"))); }
内容的提问来源于stack exchange,提问作者swaggy
相关产品推荐
相关产品推荐

