Selenium WebDriver CSS选择器帮助 - 用于选择日期

时间:2016-07-15 15:53:16

标签: css selenium

我需要从小窗口中选择日期,下面是html代码的示例。有人可以帮我通过CSSSelector或任何其他最适合这项任务的方式选择日期吗?

<td class=" " onclick="DP_jQuery_1468593787056.datepicker._selectDay('#dp1468593787059',11,2016, this);return false;">
<a class="ui-state-default" href="#">1</a>
</td>
<td class=" " onclick="DP_jQuery_1468593787056.datepicker._selectDay('#dp1468593787059',11,2016, this);return false;">
<a class="ui-state-default" href="#">2</a>
</td>
<td class=" ui-datepicker-week-end " onclick="DP_jQuery_1468593787056.datepicker._selectDay('#dp1468593787059',11,2016, this);return false;">
<a class="ui-state-default" href="#">3</a>

如有任何问题,请询问。

谢谢

1 个答案:

答案 0 :(得分:0)

对于JQueryUI DatePicker这应该有效

   public void selectDate(int day, int month, int year) {
        int currentYear = Integer.valueOf(driver.findElement(By.xpath("//td[@data-year]")).getAttribute("data-year"));
        int currentMonth = Integer.valueOf(driver.findElement(By.xpath("//td[@data-month]")).getAttribute("data-month"));

        Boolean isNext = (year == currentYear && month >= currentMonth)
                || year > currentYear;

        String navTo = isNext ? "next" : "prev";

        String dayXpath = "//td[@data-year='" + year + "' and @data-month='" + month + "'][a[text()='" + day + "']]";

        Boolean found = false;
        do {
            List<WebElement> dayEl = driver.findElements(By.xpath(dayXpath));
            if (!dayEl.isEmpty()) {
                dayEl.get(0).click();
                found = true;
                break;
            }
        } while (navigateTo(navTo));

        if (!found) {
            System.out.println("Couldn't Find the date");
        }

    }

    public Boolean navigateTo(String nav) {
        List<WebElement> navigate = driver.findElements(By.xpath("//a[@data-handler='" + nav + "']"));
        if (!navigate.isEmpty()) {
            navigate.get(0).click();
            return true;
        } else {
            System.out.println("not found" + nav);
        }
        return false;
    }

用法

    selectDate(26, 6, 1992);