Java 如何在 Selenium WebDriver 中选择日期选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21422548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:39:05  来源:igfitidea点击:

How to select the Date Picker In Selenium WebDriver

javajqueryseleniumselenium-webdriver

提问by testing

Currently working on Selenium WebDriverand using Java. I want to select values in date rangefrom the drop down.. I want to know how can I select the values as Date, Month and yearin the date picker drop down.

目前正在研究Selenium WebDriver并使用Java。我想date range从下拉列表中选择值。我想知道如何选择Date, Month and year日期选择器下拉列表中的值。

Here is the HTML tag:

这是 HTML 标签:

<dd id="date-element">
<input id="fromDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="fromDate" value="01 Jan 2013">

<input id="toDate" class="hasDatepicker" type="text" style="width:57px; padding:3px 1px; font-size:11px;" readonly="readonly" name="toDate" value="31 Dec 2013">  

enter image description here

在此处输入图片说明

The below sample code i tried:

我尝试了以下示例代码:

Log.info("Clicking on From daterange dropdown");
JavascriptExecutor executor8 = (JavascriptExecutor)driver;
executor8.executeScript("document.getElementById('fromDate').style.display='block';");
Select select8 = new Select(driver.findElement(By.id("fromDate")));
select8.selectByVisibleText("10 Jan 2013");
Thread.sleep(3000);

Log.info("Clicking on To daterange dropdown");
JavascriptExecutor executor10 = (JavascriptExecutor)driver;
executor10.executeScript("document.getElementById('toDate').style.display='block';");
Select select10 = new Select(driver.findElement(By.id("toDate")));
select10.selectByVisibleText("31 Dec 2013");
Thread.sleep(3000);

采纳答案by Ant's

DatePicker are not Selectelement. What your doing in your code is wrong.

DatePicker 不是Select元素。您在代码中所做的事情是错误的。

Datepicker are in fact table with set of rows and columns.To select a date you just have to navigate to the cell where our desired date is present.

日期选择器实际上是带有一组行和列的表。要选择一个日期,您只需导航到我们想要的日期所在的单元格。

So your code should be like this:

所以你的代码应该是这样的:

WebElement dateWidget = driver.findElement(your locator);
List<WebElement> columns=dateWidget.findElements(By.tagName("td"));

for (WebElement cell: columns){
   //Select 13th Date 
   if (cell.getText().equals("13")){
      cell.findElement(By.linkText("13")).click();
      break;
 }

回答by Shoaib Shaikh

You can try this, see if it works for you.

你可以试试这个,看看它是否适合你。

Rather than choosing date from date picker, you can enable the date box using javascript & enter the required date, this would avoid excessive time required to traverse through all date elements till you reach one you require to select.

您可以使用 javascript 启用日期框并输入所需的日期,而不是从日期选择器中选择日期,这样可以避免遍历所有日期元素直到到达需要选择的日期元素所需的时间过长。

Code for from date

起始日期代码

((JavascriptExecutor)driver).executeScript ("document.getElementById('fromDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement fromDateBox= driver.findElement(By.id("fromDate"));
fromDateBox.clear();
fromDateBox.sendKeys("8-Dec-2014"); //Enter date in required format

Code for to date

迄今为止的代码

((JavascriptExecutor)driver).executeScript ("document.getElementById('toDate').removeAttribute('readonly',0);"); // Enables the from date box

WebElement toDateBox= driver.findElement(By.id("toDate"));
toDateBox.clear();
toDateBox.sendKeys("15-Dec-2014"); //Enter date in required format

回答by pw1

try to SendKeys instead of picking the date

尝试使用 SendKeys 而不是选择日期

driver.FindElement(yourBy).SendKeys(yourDateTime.ToString("ddd, dd.MM.yyyy",CultureInfo.CreateSpecificCulture("en-US")));

If it does not work, try to send native 'tab'

如果它不起作用,请尝试发送本机“标签”

element.SendKeys(OpenQA.Selenium.Keys.Tab);

回答by Shasak Singh Sengar

public String datePicker(String object,String data){
    APP_LOGS.debug("selecting date");
    try{

        WebElement dateWidget = driver.findElement(By.xpath(OR.getProperty(object)));

        List<WebElement> rows = dateWidget.findElements(By.tagName("tr"));  
        List<WebElement> columns = dateWidget.findElements(By.tagName("td"));  

        for (WebElement cell: columns){
            if (cell.getText().equals(data)){
                cell.findElement(By.linkText(data)).click();
                break; 
            }
        }
    }catch(Exception e){
        return Constants.KEYWORD_FAIL+" -- Not able to select the date"+e.getMessage();
    }
    return Constants.KEYWORD_PASS;
}

回答by zmorris

I think this could be done in a much simpler way:

我认为这可以通过更简单的方式完成:

  1. Find the locator for the Month (use Firebug/Firepath)
  2. This is probably a Select element, use Selenium to select Month
  3. Do the same for Year
  4. Click by linkText "31" or whatever date you want to click
  1. 找到本月的定位器(使用 Firebug/Firepath)
  2. 这大概是一个Select元素,使用Selenium来选择Month
  3. 为 Year 做同样的事情
  4. 单击链接文本“31”或您要单击的任何日期

So code would look something like this:

所以代码看起来像这样:

WebElement month = driver.findElement(month combo locator);
Select monthCombo = new Select(month);
monthCombo.selectByVisibleText("March");

WebElement year = driver.findElement(year combo locator);
Select yearCombo = new Select(year);
yearCombo.selectByVisibleText("2015");

driver.click(By.linkText("31"));

This won't work if the date picker dropdowns are not Select, but most of the ones I've seen are individual elements (select, links, etc.)

如果日期选择器下拉列表不是 Select,这将不起作用,但我见过的大多数是单个元素(选择、链接等)

回答by MilanYadav

You can directly use following javascript

您可以直接使用以下javascript

((JavascriptExecutor)driver).executeScript("document.getElementById('fromDate').setAttribute('value','10 Jan 2013')")

回答by vins

Do not inject javascript. That is a bad practice.

不要注入javascript。这是一种不好的做法。

I would model the DatePicker as an element like textbox / select as shown below.

我会将 DatePicker 建模为像 textbox / select 这样的元素,如下所示。

For the detailed answer - check here- http://www.testautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/

有关详细答案 - 请在此处查看 - http://www.testautomationguru.com/selenium-webdriver-automating-custom-controls-datepicker/

public class DatePicker {

    private static final String dateFormat = "dd MMM yyyy";

    @FindBy(css = "a.ui-datepicker-prev")
    private WebElement prev;

    @FindBy(css = "a.ui-datepicker-next")
    private WebElement next;

    @FindBy(css = "div.ui-datepicker-title")
    private WebElement curDate;

    @FindBy(css = "a.ui-state-default")
    private List < WebElement > dates;

    public void setDate(String date) {

        long diff = this.getDateDifferenceInMonths(date);
        int day = this.getDay(date);

        WebElement arrow = diff >= 0 ? next : prev;
        diff = Math.abs(diff);

        //click the arrows
        for (int i = 0; i < diff; i++)
            arrow.click();

        //select the date
        dates.stream()
            .filter(ele - > Integer.parseInt(ele.getText()) == day)
            .findFirst()
            .ifPresent(ele - > ele.click());

    }

    private int getDay(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return dpToDate.getDayOfMonth();
    }

    private long getDateDifferenceInMonths(String date) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(dateFormat);
        LocalDate dpCurDate = LocalDate.parse("01 " + this.getCurrentMonthFromDatePicker(), dtf);
        LocalDate dpToDate = LocalDate.parse(date, dtf);
        return YearMonth.from(dpCurDate).until(dpToDate, ChronoUnit.MONTHS);
    }

    private String getCurrentMonthFromDatePicker() {
        return this.curDate.getText();
    }

}