<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 组件,其中包含 text
类型的 input
。我使用以下代码输入日期
。当我 headless 运行测试时,大多数时候它都会失败。
WebElement fromDate = driver.findElement(
By.tagName("md-datepicker"))
.findElement(By.tagName("input"));
if (fromDate.getAttribute("value").length() > 0) {
fromDate.clear();
}
fromDate.sendKeys(startDate);
<小时/>
在我填写的datepicker
之前还有一些其他输入
。但是当测试到达datepciker
时,它会失败,因为它可以没找到。
如何解决这个问题?
更新
我在上面的代码之前就使用了这个方法。
public static void waitUntilVisible(By locator) {
final long startTime = System.currentTimeMillis();
final Duration duration = Duration.ofSeconds(2);
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.pollingEvery(duration)
.ignoring(StaleElementReferenceException.class);
while ((System.currentTimeMillis() - startTime) < 91000) {
try {
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
break;
} catch (StaleElementReferenceException e) {
log.info("", e);
}
}
}
最佳答案
作为<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()
。
关于java - Selenium - 从 angularjs 组件中选择输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044205/