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

Selenium Java新手遇表单填充失败及CDP版本匹配问题求助

问题分析与解决方案

核心错误原因

  • 重复点击触发窗口异常:代码里连续两次点击Autocomplete按钮,第一次点击后页面已跳转到新的表单页面,原首页的Autocomplete按钮元素随之消失,第二次等待操作仍在原页面上下文查找该元素,直接抛出NoSuchWindowException。
  • CDP版本不匹配警告:你的Chrome版本为126.0.6478.115,但使用的Selenium 4.16.1内置的DevTools协议(CDP)不支持该Chrome版本,因此出现警告信息。

修正后的代码

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class SeleniumBasics {
    
public static void main(String[] args) throws InterruptedException {  
    
    WebDriver driver= new ChromeDriver();  
    driver.get("https://formy-project.herokuapp.com/");
    driver.manage().window().maximize(); 
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    
    // 等待元素可点击后仅执行一次点击,避免重复操作导致页面上下文混乱
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@class='btn btn-lg' and text()='Autocomplete']"))).click();        
    
    // 等待新页面的输入框加载可见后填充内容
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("autocomplete"))).sendKeys("1555 Park Blvd, Palo Alto, CA");
    
    Thread.sleep(1000);
    // 测试结束后关闭浏览器,释放资源
    driver.quit();
}  
}

关键修改点

  1. 移除重复点击逻辑:删除了driver.findElement(...).click()这一行,统一用WebDriverWait等待并完成点击,保证页面跳转逻辑正常。
  2. 优化输入框等待条件:将elementToBeClickable改为visibilityOfElementLocated,更精准匹配输入框的加载状态,减少无效等待。
  3. 添加资源释放操作:新增driver.quit(),避免测试结束后浏览器进程残留。

CDP版本不匹配问题解决

若要消除CDP警告,可选择以下任一方案:

  • 升级Selenium版本:将Selenium依赖升级至4.21.0及以上,该版本开始支持Chrome 126+对应的CDP版本。
  • 添加适配CDP依赖:如果不想升级Selenium,可添加适配Chrome 126的CDP依赖(Maven示例):
<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-devtools-v126</artifactId>
    <version>4.16.1</version>
</dependency>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:04:53