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

Selenium Java通过ID/Xpath定位元素报错求助

解决Selenium中ID/Xpath定位元素失败的问题

问题场景

以下是运行的Selenium Java代码:

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.support.ui.ExpectedConditions;

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(); 
        driver.findElement(By.xpath("//a[@class='btn btn-lg' and text()='Autocomplete']")).click();
        WebElement autocomplete = driver.findElement(By.id("autocomplete"));
        autocomplete.sendKeys("1555 Park Blvd, Palo Alto, CA");
        Thread.sleep(1000);
        
    }  

}

代码在Google Chrome浏览器中运行时,点击Autocomplete按钮操作正常,但执行WebElement autocomplete = driver.findElement(By.id("autocomplete"));时出现错误,错误信息如下:

juin 27, 2024 2:43:17 P.M. org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find CDP implementation matching 126
juin 27, 2024 2:43:17 P.M. org.openqa.selenium.chromium.ChromiumDriver lambda$new$5
WARNING: Unable to find version of CDP to use for 126.0.6478.115. You may need to include a dependency on a specific version of the CDP using something similar to `org.seleniumhq.selenium:selenium-devtools-v86:4.16.1` where the version ("v86") matches the version of the chromium-based browser you're using and the version number of the artifact is the same as Selenium's.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#autocomplete"}
  (Session info: chrome=126.0.6478.115)
For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Build info: version: '4.16.1', revision: '9b4c83354e'
System info: os.name: 'Windows 11', os.arch: 'amd64', os.version: '10.0', java.version: '22'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [b7a6e061f82aac92c3ac81d291082ca6, findElement {using=id, value=autocomplete}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 126.0.6478.115, chrome: {chromedriverVersion: 126.0.6478.126 (d36ace6122e..., userDataDir: C:\Users\Kamilia\AppData\Lo...}, fedcm:accounts: true, goog:chromeOptions: {debuggerAddress: localhost:52425}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: windows, proxy: Proxy(), se:cdp: ws://localhost:52425/devtoo..., se:cdpVersion: 126.0.6478.115, 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: b7a6e061f82aac92c3ac81d291082ca6
    at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:62)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:502)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:486)
    at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)
    at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)
    at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:52)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:191)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:200)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:175)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:523)
    at org.openqa.selenium.remote.ElementLocation$ElementFinder$2.findElement(ElementLocation.java:165)
    at org.openqa.selenium.remote.ElementLocation.findElement(ElementLocation.java:66)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:360)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:354)
    at SeleniumBasics.main(SeleniumBasics.java:15)

解决方案

1. 修复元素定位失败问题

出现NoSuchElementException的核心原因是点击按钮跳转页面后,目标元素还未完成加载就执行了定位操作,Thread.sleep(1000)的等待时间不可靠,可能不足以让元素渲染完成。改用显式等待可以确保元素出现后再进行操作:

修改后的代码如下:

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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;

public class SeleniumBasics {
    
public static void main(String[] args) {  
        
        WebDriver driver= new ChromeDriver();  
        driver.get("https://formy-project.herokuapp.com/");
        driver.manage().window().maximize(); 
        driver.findElement(By.xpath("//a[@class='btn btn-lg' and text()='Autocomplete']")).click();
        
        // 显式等待元素可见,最长等待10秒
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        WebElement autocomplete = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("autocomplete")));
        autocomplete.sendKeys("1555 Park Blvd, Palo Alto, CA");
        
        driver.quit(); // 记得关闭浏览器
        
    }  

}

2. 解决CDP版本不匹配警告

错误日志中的CDP警告是因为Selenium 4.16.1不支持Chrome 126版本的CDP协议,有两种解决方式:

  • 升级Selenium版本:将Selenium依赖升级到4.21.0及以上版本(该版本开始支持Chrome 126)。如果使用Maven,修改pom.xml中的依赖:
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.21.0</version>
    </dependency>
    
  • 添加对应CDP依赖:如果不想升级Selenium,添加Chrome 126对应的CDP依赖:
    <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 19:20:11