Selenium Java如何获取日历控件结束日期并按范围规则选择日期
Selenium Java 日历控件范围校验与选择实现方案
核心逻辑
日历可选范围固定为当前日期起11天,无需从DOM结构爬取结束日期,直接通过Java内置时间API计算范围即可,实现更稳定高效。
前置说明
- 需确保传入的
date参数格式、日历控件上的日期文本格式完全一致,例如统一为yyyy-MM-dd、dd/MM/yyyy等 - 代码中已默认
currentDate是定位到class="owl-dt-calendar-cell-content owl-dt-calendar-cell-today"的页面元素
完整实现代码
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public void selectRequiredOn(String date) { // 点击唤起日历控件 requiredOnClick.click(); // 格式化器:请根据实际页面的日期格式修改pattern DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); try { // 获取页面当前日期文本并转成LocalDate String todayStr = currentDate.getText().trim(); LocalDate today = LocalDate.parse(todayStr, dateFormatter); // 计算可选范围结束日期:当前日期+10天,共11天可选(含当天) LocalDate maxAvailableDate = today.plusDays(10); // 把传入的目标日期转成LocalDate LocalDate targetDate = LocalDate.parse(date.trim(), dateFormatter); // 判断是否在可选范围内 if ((targetDate.isEqual(today) || targetDate.isAfter(today)) && (targetDate.isEqual(maxAvailableDate) || targetDate.isBefore(maxAvailableDate))) { // 在范围内:定位对应日期元素并点击,XPath可根据实际DOM结构调整 WebElement targetDateElement = driver.findElement( By.xpath("//div[contains(@class,'owl-dt-calendar-cell-content') and text()='" + date + "']") ); targetDateElement.click(); } else { // 不在范围内:点击当前日期 currentDate.click(); } } catch (DateTimeParseException e) { // 日期解析失败时默认选择当前日期,可根据业务需求调整异常处理逻辑 currentDate.click(); e.printStackTrace(); } }
关键注意点
- 请根据页面实际显示的日期格式修改
DateTimeFormatter的pattern参数,避免日期解析失败 - 目标日期元素的定位逻辑可根据实际DOM结构调整,若日期文本包含其他特殊字符可优化定位规则
- 若日历控件存在跨月的情况,需额外增加月份切换的逻辑,保证目标日期在当前可见的日历面板中
内容的提问来源于stack exchange,提问作者RASHI
相关产品推荐
相关产品推荐

