无效的元素状态:元素必须是用户可编辑的,以清除尝试使用Selenium在下拉式切换中单击并插入日期的错误

问题描述 投票:2回答:2

我正在尝试单击此日历并使用硒自动插入日期,但出现以下错误:

无效的元素状态:元素必须是用户可编辑的,以便清除它。

HTML片段

<a id="enddate-dropdown" class="dropdown-toggle" role="button" data-toggle="dropdown" data-target="">
                <p class="custom-datepickers__date-prefix ng-binding">To:</p>
                <!-- ngIf: displayEndDate -->
                <!-- ngIf: !displayEndDate --><div ng-if="!displayEndDate" class="custom-datepickers__no-date ng-scope"></div><!-- end ngIf: !displayEndDate -->
</a>

代码段

myclass.SetDateByXpath("//*[@id=\"enddate-dropdown\"]/p", myclass.GetDate("yyyy/MM/dd", mydate));

public void SetDateByXpath(String element, String value)
    {
        WebElement webElement = ExplicitWaitOnElement(By.xpath(element));       
        ((JavascriptExecutor) driver).executeScript(
                "arguments[0].removeAttribute('readonly','readonly')",webElement);
        webElement.clear();
        webElement.sendKeys(value);
    }

如果我手动设置日期,则为HTML:

<a id="enddate-dropdown" class="dropdown-toggle" role="button" data-toggle="dropdown" data-target="">
                <p class="custom-datepickers__date-prefix ng-binding">To:</p>
                <!-- ngIf: displayEndDate --><p ng-if="displayEndDate" class="ng-binding ng-scope">2019/11/21</p><!-- end ngIf: displayEndDate -->
                <!-- ngIf: !displayEndDate -->
</a>

可能网站已更改,但是现在我不知道如何设置该值。任何帮助将不胜感激。

谢谢

angular selenium selenium-webdriver webdriverwait expected-condition
2个回答
2
投票

此错误消息...

invalid element state: Element must be user-editable in order to clear it.

...表示所标识的元素不在user-editable状态下以调用clear()方法。


要在带有Angular元素的下拉键中插入日期,有两种方法:

  • 您既可以在日历上单击click(),也可以使用sendKeys()插入日期
  • 或者您可以使用executeScript()调用readonly属性的removeAttribute()

但是,根据您共享的HTML,似乎在日期字符串中填充了元素,即2019/11/21HTML DOM中不可用。因此,我们可以推断出,由于与其他WebElements的交互作用,以下元素被添加到DOM Tree中,如下所示:

<p ng-if="displayEndDate" class="ng-binding ng-scope">2019/11/21</p>

因此最好的方法是,>

  • 首先在HTML诱导WebDriverWait中易于使用的元素上调用click()
  • 下一步在新创建的元素WebDriverWait
  • 上调用sendKeys()
  • 代码块:

//element -> myclass.SetDateByXpath("//a[@class='dropdown-toggle' and @id='enddate-dropdown']"
// observe the change in the ^^^ xpath ^^^
//value -> myclass.GetDate("yyyy/MM/dd", mydate));

public void SetDateByXpath(String element, String value)
{
    WebElement webElement = ExplicitWaitOnElement(By.xpath(element));       
    webElement.click();
    WebElement webElement_new = ExplicitWaitOnElement(By.xpath("//a[@class='dropdown-toggle' and @id='enddate-dropdown']//p[@class='ng-binding ng-scope' and @ng-if='displayEndDate']"));
    webElement_new.clear();
    webElement_new.sendKeys(value);
}

参考

您可以在以下位置找到相关的讨论:


5
投票

我猜你的错误正在被抛出:

© www.soinside.com 2019 - 2024. All rights reserved.