<md-datepicker ng-model="mc.date.from" required="" md-val="">
<span class="input-group date" style="width:144px">
<input size="16" type="text"
class="form-control"
autocomplete="off">
<span class="input-group-btn">
<button class="btn btn-default" tabindex="-1" >
<i class="glyphicon glyphicon-calendar"></i>
</button>
</span>
</span>
</md-datepicker>
我有一个AngularJs组件,其中包含类型input
的{{1}}。我已使用以下代码输入text
。当我无头运行测试时,大多数情况下都会失败。
date
我要填写的WebElement fromDate = driver.findElement(
By.tagName("md-datepicker"))
.findElement(By.tagName("input"));
if (fromDate.getAttribute("value").length() > 0) {
fromDate.clear();
}
fromDate.sendKeys(startDate);
之前还有其他一些inputs
。但是,当测试达到datepicker
时,它就会失败,因为找不到它。
如何解决此问题?
在上面的代码之前,我已经使用了此方法。
datepciker
答案 0 :(得分:2)
由于<input>
元素是Angular元素,因此您必须诱使 WebDriverWait 才能使所需的元素可点击,并且可以使用以下任一解决方案:
cssSelector
:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("md-datepicker[ng-model$='from']>span.input-group.date>input.form-control")));
elem.click();
elem.clear();
elem.sendKeys(startDate);
xpath
:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//md-datepicker[contains(@ng-model,'from')]/span[@class='input-group date']/input[@class='form-control']")));
elem.click();
elem.clear();
elem.sendKeys(startDate);
根据您的问题更新功能waitUntilVisible()
在我看来presenceOfElementLocated()
实现 FluentWait 时忽略了 StaleElementReferenceException ,通过特制的 WebDriverWait 和 ExpectedConditions 为 elementToBeClickable()
可以轻松实现。
答案 1 :(得分:0)
您可以尝试等待元素的可见性:
WebElement fromDate =
new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("md-datepicker input")));
答案 2 :(得分:0)
您可以尝试使用cssSelector
,不建议在执行headless
时使用xpath
WebElement fromDate = driver.findElement(
By.cssSelector(".input-group.date"))
.findElement(By.cssSelector(".form-control"));
if (fromDate.getAttribute("value").length() > 0) {
fromDate.clear();
}
fromDate.sendKeys(startDate);
答案 3 :(得分:0)
我只能在try catch块中捕获StaleElementReferenceException
来解决此问题。
WebElement input;
try {
input = driver.findElement(
By.tagName("md-datepicker"))
.findElement(By.tagName("input"));
} catch(StaleElementReferenceException e) {
input = driver.findElement(By.xpath("//md-datepicker/span/input"));
}
if (input.getAttribute("value").length() > 0) {
input.clear();
}
正如我在问题中所述,我使用waitUntilVisible
方法来等待输入的存在。
我在2018年10月29日问了这个问题。当时,我正在使用硒版本3.14.0
。但是这种方法不会选择输入,也不应该使用硒版本3.141.0
。