我正在尝试使用 while 循环从 SPICEJET 网站的“出发日期”字段中选择特定月份。当到达特定月份时,我将退出 while 循环,然后从特定月份中选择一个日期。在下面的代码中,我观察到 while 循环在无限循环中运行,并且在到达特定月份时不会停止。
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)']");
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() {
//click the departure date
driver.findElement(By.xpath("(//div[@data-testid='departure-date-dropdown-label-test-id']/div/div)[2]")).click();
//store the departure month value
String departMonthValue = driver.findElement(By.xpath(
"//div[contains(@data-testid,'undefined-month')]/child::div/div[contains(normalize-space(),'June')]"))
.getText();
System.out.println(departMonthValue);
//click the forward arrow until departure month is August 2024
while (!departMonthValue.trim().contains("August 2024")) {
driver.findElement(forwardArrow).click();
departMonthValue = driver.findElement(By.xpath(
"//div[contains(@data-testid,'undefined-month')]/child::div/div[contains(normalize-space(),'July')]"))
.getText();
}
//select the date
driver.findElement(By.xpath("//div[contains(@data-testid,'undefined-month')]//div[text()='28']")).click();
}
}
我将你的方法重写为通用的......或更灵活。它采用
LocalDate
来保存出发日期的日-月-年。如果出发日期在今天之前,则会抛出异常。如果出发日期有效,它将在月份面板中移动,直到看到所需的日月,然后单击正确的日期。
public void selectDepartureDate(LocalDate departureDate) {
if (departureDate.isBefore(LocalDate.now())) {
throw new InvalidParameterException("The departure date must be in the future.");
}
// open the Departure Date calendar
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div[data-testid='departure-date-dropdown-label-test-id']"))).click();
// move the calendar to the desired month
int clicks = (int) LocalDate.now().until(departureDate, ChronoUnit.MONTHS) / 2;
for (int i = 0; i < clicks; i++) {
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("[data-testid='undefined-calendar-picker'] > div"))).click();
}
// select the desired day
String month = departureDate.getMonth().toString();
month = month.substring(0,1).toUpperCase() + month.substring(1).toLowerCase();
String dataTestId = String.format("undefined-month-%s-%s", month, departureDate.getYear());
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format("//div[@data-testid='%s']//div[text()='%s']", dataTestId, departureDate.getDayOfMonth())))).click();
}
你这样称呼它
String url = "https://www.spicejet.com";
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get(url);
LocalDate departureDate = LocalDate.of(2024, Month.AUGUST, 28);
selectDepartureDate(departureDate);
其中
WebDriver driver;
在类中声明,但您可以根据需要更改它。我只是不想将 driver
传递给我的所有方法。