[英]Selenium StaleElementException after refilling in form after submission
我有一個表格,我正在嘗試自動填寫我的Selenium腳本之一。 有一個表單,其中包含大約4個文本字段,HTML看起來像這樣
<input class="class" id="id" name="name" value="" autocomplete="off" wtx-context="stuff" type="text">
然后,在填寫完這些表格后,有一個輸入提交按鈕,其中包含以下HTML代碼
<input id="id2" class="class2" value="Add Material" wtx-context="morestuff" type="submit">
我已經使用了以下Java代碼,並且成功地填寫了表單並提交了表單,但是一旦提交了表單,我假設發生的事情是在DOM上刷新了表單,然后拋出了StaleElement異常。 我已經通過進入首頁並使用表單導航回網頁的方式來解決問題,但是如果有人知道,我正在尋找一種更優雅的解決方案。 下面是我的Java代碼。
Page.WriteToField(Page.Input_number(), "111111111");
Page.WriteToField(Page.Input_number2(), "222222222");
Page.WriteToField(Page.Input_date(), format.format(cal.getTime()));
Page.WriteToField(Page.Input_number3(), "3333");
Page.SubmitIngredient();
WriteToField()函數看起來像這樣
public void WriteToField(WebElement field, String text) {
field.click();
field.clear();
field.sendKeys(text);
}
然后,我使用以下格式從我的頁面類訪問所有WebElements
public WebElement Input_number() {
return wait.until(ExpectedConditions.elementToBeClickable(By.id("form1")));
}
在實際檢查元素是否可單擊之前,為什么不嘗試檢查元素的存在?
public WebElement Input_number() {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("form1")));
return wait.until(ExpectedConditions.elementToBeClickable(By.id("form1")));
}
更新-我要求添加元素存在的期望條件的原因是它確實再次執行了查找元素操作。 [請參考下面的presenceOfElementLocated
方法的實現]因此,我希望有人可以得到元素作為回報。 [但是我可能錯了]
public static ExpectedCondition<WebElement> presenceOfElementLocated(final By locator) {
return new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver driver) {
return ExpectedConditions.findElement(locator, driver);
}
public String toString() {
return "presence of element located by: " + locator;
}
};
}
除此之外,如果您檢查elementToBeClickable
方法的實現[在代碼塊下面],它將不執行查找操作,並且如果元素不可見或未啟用,則會引發StaleElementReferenceException
異常。
public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) {
return new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver driver) {
WebElement visibleElement = (WebElement)ExpectedConditions.visibilityOf(element).apply(driver);
try {
return visibleElement != null && visibleElement.isEnabled()?visibleElement:null;
} catch (StaleElementReferenceException var4) {
return null;
}
}
public String toString() {
return "element to be clickable: " + element;
}
};
}
因此,在檢查元素是否可見之前檢查元素的存在對我來說很有意義[正如我之前所說,我可能是錯誤的]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.