【问题标题】:Not able to input date using sendKeys in Selenium WebDriver无法在 Selenium WebDriver 中使用 sendKeys 输入日期
【发布时间】:2012-09-07 07:30:37
【问题描述】:

日期字段就像一个日历,我无法使用 Selenium WebDriver 的 sendKeys 输入日期。

但是在使用 Selenium RC 之前,日期字段中的“类型”可以正常工作。

我尝试在“sendKeys()”之前使用“clear()”,但这给出了错误:

Caught Exception: Element is read-only and so may not be used for actions
Command duration or timeout: 10.11 seconds

sendKeys() 适用于其他文本输入字段。

我尝试了 isDisplayed() 来检查元素,它是真的。即使在浏览器中,运行测试时,光标也会转到日期字段,但不会在其中输入任何文本。

【问题讨论】:

  • 我遇到了同样的问题,但是对于 Telerik 的 RadCalendar (.NET),对我来说,这个问题是通过物理上使用日历来模拟点击日期来解决的。
  • 我遇到了这个博客 [blog.reallysimplethoughts.com/2012/07/19/… 这说“sendKeys 模拟真实用户键入指定字符串中的每个字符;它还受到真实用户的限制,例如无法键入不可见或只读元素。”因此,对于我的应用来说,似乎无法在日期字段中输入内容。谁能建议任何其他解决方法来从日历中选择日期?
  • 直接解决方案就像@Arran 所说的那样。您应该模拟用户选择日期。我不知道其他解决方法。
  • 由于我的是数据驱动框架,模拟点击日期(动态)会有点困难。我通过使用 JavascriptExecutor 来完成这项工作,例如:((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]", driver.findElement(By.id(stringc3)), stringc4); 其中 stringc3 是日期字段的定位器 ID,而 stringc4 是日期,例如“01-01-2012”

标签: java selenium-webdriver


【解决方案1】:

为此使用以下代码...

((JavascriptExecutor)driver).executeScript ("document.getElementById('dateofbirth').removeAttribute('readonly',0);");

WebElement BirthDate= driver.findElement(By.id("dateofbirth"));
BirthDate.clear();
BirthDate.sendKeys("20-Aug-1985"); //Enter this date details with valid date format

【讨论】:

  • 很好的解决方案,只需通过声明 driver =new HtmlUnitDriver(true); 来确保启用了 javascript
【解决方案2】:

我也遇到了同样的问题。这就是我找到的解决方案。这对我来说很好。 只需删除输入字段的只读属性,然后与其他输入字段一样。

   ((JavascriptExecutor) driver).executeScript("document.getElementsByName('date'[0].removeAttribute('readonly');");
    WebElement dateFld = driver.findElement(By.id("date_completed"));
    dateFld.clear();
    dateFld.sendKeys("date Completed");

【讨论】:

    【解决方案3】:

    对于此线程的未来读者,@Flaburgan 发布的问题解决方案 https://github.com/mozilla/geckodriver/issues/1070 被发现可以在 Win7-64 上使用 Firefox 63

    “作为记录,看起来具有正确格式的 ISO 日期 (yyyy-mm-dd) 的 send_keys 可以工作。因此,对于您的示例,您能否尝试使用 (like) 2012-11-02 调用 send_keys?”

    【讨论】:

      【解决方案4】:

      如果您使用的是 jQuery 日期选择器对象,则该字段应该是只读的,并且必须从日历对象中选择日期。在这种情况下,您可以使用 Selenium Web Driver 的“选择”类方法来选择日期。

      Select date = new Select(driver.findElement(By.linkText("the date want to select")));
      date.click();
      

      【讨论】:

        【解决方案5】:

        我已经这样做了,效果很好。注意格式。这样你甚至可以从控件中获取值。

        var dob = element(by.id('dateOfBirth'))
        dob.sendKeys('20-08-1985');
        
        expect(element(by.id('dateOfBirth')).getAttribute('value')).toBe('2015-20-08');
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-22
          • 2013-09-25
          • 1970-01-01
          • 1970-01-01
          • 2012-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多