![](/img/trans.png)
[英]How do I avoid StaleElementException after WebElement.click() for an ajax button?
[英](StaleElementException:Selenium) How do I handle this?
這是我第一天第一次從事硒研究,也沒有深入的Web技術經驗。
解決方法,在嘗試訪問DOM上的特定對象時,我一直面臨StaleElementException。
以下方法處理所有任務:
private void extract(WebDriver driver) {
try {
List<WebElement> rows = driver.findElements(By.xpath("//*[@id='gvSearchResults']/tbody/tr"));
for (WebElement row : rows) {
WebElement columns = row.findElement(By.xpath("./td[1]/a"));
if (assertAndVerifyElement(By.xpath("//*[@id='gvSearchResults']/tbody/tr/td[1]/a"))) {
columns.click();
}
List<WebElement> elements = driver
.findElements(By.xpath("//*[@id='ctl00_MainContent_pnlDetailsInd']/table/tbody/tr"));
for (WebElement element : elements) {
WebElement values = element.findElement(By.xpath("./td[1]"));
System.out.print(values.getText() + " ");
WebElement values2 = element.findElement(By.xpath("./td[2]"));
System.out.println(values2.getText());
}
if(assertAndVerifyElement(By.xpath("//*[@id='ctl00_MainContent_btnBack']")))
driver.findElement(By.xpath("//*[@id='ctl00_MainContent_btnBack']")).click();
}
} catch (Exception e) {
e.printStackTrace();
}
}
斷言邏輯在這里:
public boolean assertAndVerifyElement(By element) throws InterruptedException {
boolean isPresent = false;
for (int i = 0; i < 5; i++) {
try {
if (driver.findElement(element) != null) {
isPresent = true;
break;
}
} catch (Exception e) {
// System.out.println(e.getLocalizedMessage());
Thread.sleep(1000);
}
}
Assert.assertTrue("\"" + element + "\" is not present.", isPresent);
return isPresent;
}
我嘗試過很少的解決方案,要求我使用等到預期的條件,但沒有一個起作用。
此外,如果您指出我在以上示例中可能使用的任何不良設計做法,也將不勝感激。
我可以給你克服陳舊的想法。
通常,如果在啟動Webelement后更改了元素屬性或某些內容,則將獲得Stale Exception。 例如,在某些情況下,如果用戶嘗試在同一頁面上單擊同一元素,但在頁面刷新后單擊,則會獲得跟蹤例外。
為了克服這個問題,我們可以創建新的Web元素,以防頁面被更改或刷新。 下面的代碼可以給您一些想法。
例:
webElement element = driver.findElement(by.xpath("//*[@id='StackOverflow']"));
element.click();
//page is refreshed
element.click();//This will obviously throw stale exception
為了克服這個問題,我們可以將xpath存儲在某個字符串中,並在使用時使用它創建一個新的webelement。
String xpath = "//*[@id='StackOverflow']";
driver.findElement(by.xpath(xpath)).click();
//page has been refreshed. Now create a new element and work on it
driver.findElement(by.xpath(xpath)).click(); //This works
另一個例子:
for(int i = 0; i<5; i++)
{
String value = driver.findElement(by.xpath("//.....["+i+"]")).getText);
System.out.println(value);
}
希望這對您有所幫助。 謝謝
當所討論的Web元素在dom上更改並且丟失對該Webelement的初始引用時,將發生StaleElementException。
您可以再次搜索網絡元素
嘗試這個
try:
element = self.find_element_by_class('')
element.click()
except StaleElementReferenceException:
element = self.find_element_by_class('')
element.click()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.