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

如何使用Selenium从日期选择器中选取日期?已遇NoSuchElementException

解决日期选择器NoSuchElementException异常的方案

你的问题出在两个核心点:一是固定延迟的Thread.sleep无法保证日期选择器完全加载;二是元素定位器写法不准确,导致找不到目标元素。以下是修正后的实现方案:

修正后的代码

首先导入必要的依赖包:

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;

主逻辑代码:

WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://rahulshettyacademy.com/dropdownsPractise/");

// 选择出发地与目的地
driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
driver.findElement(By.xpath("//a[@value='BLR']")).click();
driver.findElement(By.xpath("(//a[@value='MAA'])[2]")).click();

// 显式等待日期选择器加载完成,定位并点击当天日期
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement todayDate = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".ui-state-default.ui-state-highlight")));
todayDate.click();

driver.quit();

关键修正说明

  • 替换固定延迟为显式等待:WebDriverWait会等待元素可点击后再执行操作,比Thread.sleep更可靠,避免因页面加载慢导致元素未出现的问题
  • 修正CSS选择器写法:原选择器a[class='ui-state-default ui-state-highlight']要求class属性完全匹配,而页面中日期元素的class可能动态变化。改用.ui-state-default.ui-state-highlight,只要元素包含这两个class即可匹配,兼容性更强
  • 选择其他日期的方法:如果需要选择非当天的日期,可通过XPath定位具体日期文本,比如选择15号:
    WebElement targetDate = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//td[@data-handler='selectDay']/a[text()='15']")));
    targetDate.click();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 01:30:09