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

使用Selenium Java点击元素时频繁触发WebDriverException加载状态错误

Selenium Java自动化测试随机卡顿报错排查与解决

问题场景与报错信息

在Eclipse中使用Selenium结合Java执行多步点击的自动化测试时,频繁在随机阶段卡住,抛出如下错误:

Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: cannot determine loading status
from unknown error: unexpected command response
  (Session info: chrome=103.0.5060.114)
Build info: version: '4.3.0', revision: 'a4995e2c09*'
System info: host: 'AWAIS-PC', ip: '192.168.1.62', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '18.0.1'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Command: [379a531d077c5128f9ab7816b39e5bdd, clickElement {id=6b67a9d0-7b57-4279-a7e4-b1e917a94925}]
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 103.0.5060.114, chrome: {chromedriverVersion: 103.0.5060.53 (a1711811edd7..., userDataDir: C:\Users\WRP\AppData\Local\...}, goog:chromeOptions: {debuggerAddress: localhost:61026}, networkConnectionEnabled: false, pageLoadStrategy: normal, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:61026/devtoo..., se:cdpVersion: 103.0.5060.114, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Element: [[ChromeDriver: chrome on WINDOWS (379a531d077c5128f9ab7816b39e5bdd)] -> css selector: button[class='CartTotal-secureCheckout'] span]
Session ID: 379a531d077c5128f9ab7816b39e5bdd
    at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
    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:53)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:569)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:257)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:78)
    at First_Test.Practice_First.main(Practice_First.java:125)

测试代码如下:

WebDriver driver = new ChromeDriver();
WebDriverWait waits = new WebDriverWait(driver, Duration.ofSeconds(10));
//driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
//Thread.sleep(3000);
driver.manage().window().maximize();
//Thread.sleep(3000);
//  String originalWindow=  driver.getWindowHandle();
// Thread.sleep(5000);
waits.until(ExpectedConditions.visibilityOfElementLocated(By.id("wzrk-cancel")));
//waits.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#wzrk-cancel")));
driver.findElement(By.id("wzrk-cancel")).click();

// driver.findElement(By.xpath("//button[@id='wzrk-cancel']")).click();
waits.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href*='/men']")));
driver.findElement(By.cssSelector("a[href*='/men']")).click();

JavascriptExecutor Js1 = (JavascriptExecutor) driver;
Js1.executeScript("window.scrollBy(0,2500)");

waits.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[normalize-space()='Hibiscus Camo Arch Logo T-shirt in Cotton']")));
Thread.sleep(1000);
driver.findElement(By.xpath("//div[normalize-space()='Hibiscus Camo Arch Logo T-shirt in Cotton']")).click();

waits.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[title='Blue']")));
driver.findElement(By.cssSelector("button[title='Blue']")).click();

//waits.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//button[@title='Blue']")));
// driver.findElement(By.xpath("//button[@title='Blue']")).click();
driver.findElement(By.xpath("//div[@class='Select-control']")).click();
driver.findElement(By.xpath("//*[text()='XL']")).click();
Thread.sleep(1000);
driver.findElement(By.cssSelector("[data-cy^='addToBagButton']")).click();
Thread.sleep(2000);
waits.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[class='Select-control']")));
driver.findElement(By.xpath("//div[@class='Select-control']")).click();
driver.findElement(By.xpath("//*[text()='L']")).click();
driver.findElement(By.cssSelector("[data-cy^='addToBagButton']")).click();
Thread.sleep(1000);
// waits.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[class^='Select-control']")));

waits.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[normalize-space()='GO TO BAG']")));
Thread.sleep(1000);
driver.findElement(By.xpath("//a[normalize-space()='GO TO BAG']")).click();

// driver.findElement(By.xpath("//span[normalize-space()='Secure Checkout']")).click();
waits.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button[class='CartTotal-secureCheckout'] span")));
driver.findElement(By.cssSelector("button[class='CartTotal-secureCheckout'] span")).click();
//  Thread.sleep(2000);
waits.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".Map-enterAddressManuallyButton")));
driver.findElement(By.cssSelector(".Map-enterAddressManuallyButton")).click();

driver.findElement(By.xpath("//label[@for='regionId']//div[@class='Select Dropdown has-value is-searchable Select--single']")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[text()='Ajman']")).click();

核心解决方案

1. 强制版本兼容匹配

  • Chrome浏览器版本(103.0.5060.114)必须与ChromeDriver版本完全一致,当前报错中ChromeDriver为103.0.5060.53,小版本差异会导致通信异常,需更换为103.0.5060.114版本的ChromeDriver
  • 推荐使用WebDriverManager自动管理驱动版本,避免手动匹配错误:
    // 添加Maven依赖:<dependency><groupId>io.github.bonigarcia</groupId><artifactId>webdrivermanager</artifactId><version>5.3.2</version></dependency>
    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    

2. 彻底移除硬等待,优化显式等待策略

  • 删除所有Thread.sleep(),改用WebDriverWait的elementToBeClickable()替代visibilityOfElementLocated(),确保元素处于可交互状态再执行操作
  • 示例优化后的点击逻辑:
    // 替换原来的等待+硬等待+点击
    WebElement secureCheckoutBtn = waits.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button[class='CartTotal-secureCheckout'] span")));
    secureCheckoutBtn.click();
    

3. 修改页面加载策略

  • 默认的normal加载策略会等待所有资源加载完成,对于动态页面可改为EAGER(等待DOM加载完成)或NONE(不等待),减少不必要的等待:
    ChromeOptions options = new ChromeOptions();
    options.setPageLoadStrategy(PageLoadStrategy.EAGER);
    WebDriver driver = new ChromeDriver(options);
    

4. 优化元素定位器稳定性

  • 优先使用id、data-cy等静态属性定位元素,避免依赖动态生成的class或文本内容
  • 示例:将By.xpath("//div[normalize-space()='Hibiscus Camo Arch Logo T-shirt in Cotton']")改为如果有data-cy属性则用By.cssSelector("[data-cy='product-title']")(需根据实际页面调整)

5. 优化JavaScript执行后的等待

  • 执行滚动操作后,等待目标元素进入视口再点击,避免因元素未在可见区域导致的交互失败:
    WebElement targetProduct = waits.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[normalize-space()='Hibiscus Camo Arch Logo T-shirt in Cotton']")));
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", targetProduct);
    waits.until(ExpectedConditions.elementToBeClickable(targetProduct)).click();
    

内容的提问来源于stack exchange,提问作者Zamir Sultan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:48:18