我有一种情况,我必须从日历中选择3天回溯日期。如何使用selenium来自动执行此情况。我正在将Java与selenium一起使用进行自动化。
1)假设您可以在输入字段中输入日期,而日历仅是图标。你可以有这样的帮助方法
public String threeDaysBefore(){ String threeDaysBefore = ""; Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DAY_OF_YEAR, -3); Date before = cal.getTime(); SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm"); threeDaysBefore = formatter.format(before); return threeDaysBefore; }
然后在代码中
WebElement calendarManualInput = driver.findElement...// find the manual input field calendarManualInput.sendKeys(threeDaysBefore());
2)如果您只能单击日历,那将更加棘手。您仍然需要String,但有一点不同:
public String threeDaysBefore(){ String threeDaysBefore = ""; Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DAY_OF_YEAR, -3); Date before = cal.getTime(); SimpleDateFormat formatter = new SimpleDateFormat("dd"); threeDaysBefore = formatter.format(before); return threeDaysBefore; }
但是,上面没有什么收获。如果日期是1.4。那么它将返回“ 29”,可以解释为29.4。你不想发生。因此,在代码后面,您可能必须这样做
//this will click three days before Date today = new Date(); Date minusThree = new Date(); Calendar now = Calendar.getInstance(); now.setTime(today); Calendar before = Calendar.getInstance(); before.setTime(minusThree); before.add(Calendar.DAY_OF_YEAR, -3); int monthNow = now.get(Calendar.MONTH); int monthBefore = before.get(Calendar.MONTH); if (monthBefore < monthNow){ // click previous month in the calendar tooltip on page } WebElement dateToSelect = driver.findElement(By.xpath("//span[text()='"+threeDaysBefore()+"']")); dateToSelect.click();