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

SpiceJet日历处理:Selenium+Java日期选择无限循环问题排查

SpiceJet日历选择无限循环问题修复

问题根源

你的代码陷入无限循环的核心原因是硬编码了月份名称到XPath中:

  • 初始获取月份时,XPath限定只找包含"June"的元素;切换月份后,循环里又硬编码找包含"July"的元素,永远无法定位到"August 2024"对应的元素,导致循环条件永远为真。
  • 缺少等待机制,点击前进箭头后日历未完成更新就立即获取文本,可能拿到旧的月份值。

修复后的代码

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

public class CalendarHandling {

    static WebDriver driver;
    static By forwardArrow = By.xpath("//*[local-name()='svg' and @data-testid='svg-img']//*[name()='g' and @transform='translate(1 1)']");
    // 通用定位年月显示元素,不硬编码月份
    static By currentMonthYear = By.xpath("//div[contains(@data-testid,'undefined-month')]/child::div/div[1]");

    public static void main(String[] args) {
        BrowserUtil butil = new BrowserUtil();
        driver = butil.launchBrowser("chrome");
        butil.launchURL("https://www.spicejet.com/");
        selectDepartDate();
    }

    public static void selectDepartDate() {
        // 点击出发日期框
        driver.findElement(By.xpath("(//div[@data-testid='departure-date-dropdown-label-test-id']/div/div)[2]")).click();

        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        String departMonthValue = wait.until(ExpectedConditions.visibilityOfElementLocated(currentMonthYear)).getText().trim();
        System.out.println("当前月份:" + departMonthValue);

        // 循环点击箭头直到目标月份
        while (!departMonthValue.equals("August 2024")) {
            wait.until(ExpectedConditions.elementToBeClickable(forwardArrow)).click();
            // 等待月份更新后再获取文本
            departMonthValue = wait.until(ExpectedConditions.visibilityOfElementLocated(currentMonthYear)).getText().trim();
            System.out.println("切换后月份:" + departMonthValue);
        }

        // 选择日期
        wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(@data-testid,'undefined-month')]//div[text()='28']"))).click();
    }
}

关键改进点

  • 移除硬编码月份的XPath:使用通用定位器currentMonthYear定位日历顶部的年月显示元素,确保每次都能获取当前显示的年月。
  • 添加显式等待:使用WebDriverWait等待元素可见/可点击,避免因页面加载延迟导致获取旧数据或元素不可交互。
  • 精确匹配月份文本:用equals替代contains,避免因文本格式变化(如多余空格)导致判断错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 23:32:19