在我使用 selenium 网络驱动程序的 C# 应用程序中,我遇到了这个错误:
OpenQA.Selenium.StaleElementReferenceException: stale element 引用:元素未附加到页面文档中
在此代码中:
IWebElement e = driver.FindElement(By.XPath(link_click), 10);
e.Click();
错误行出现在 e.Click()
中,但这是一个在 XPath 指定的同一链接中成功执行的过程,但最后一次尝试却失败了!那么这个错误是什么意思,如何解决?
这意味着,要么页面中的元素发生了变化,要么元素被删除,完整参考链接 http://www.seleniumhq.org/exceptions/stale_element_reference.jsp
处理这种情况的一种方法是重试,可能类似于
bool staleElement = true;
while(staleElement){
try{
driver.FindElement(By.XPath(link_click), 10).Click();
staleElement = false;
} catch(StaleElementReferenceException e){
staleElement = true;
}
}
我在一个网站上做日期选择器时也遇到了同样的问题。我需要从日期选择器中获取所有激活(或启用)的按钮,然后点击每个按钮。 当我重复使用这些元素时,效果越来越差。 我又重新重申了另一个列表。 出现这种情况可能是因为一旦 List
@Test
public void datePickerTest() throws InterruptedException{
driver.get(baseURL);
// click on flights tab
genericMethod.getElement("tab-flight-tab-hp", "id").click();
// click departing date, such that the date picker is loaded in the dom
genericMethod.getElement("flight-departing-hp-flight", "id").click();
Thread.sleep(700);
// pass the collected xpath where you can find all the dates which are enabled
String xpath=".//*[@id='flight-departing-wrapper-hp-flight']/div/div/div[2]/table/tbody/tr/td/button[not(@disabled)]";
List<WebElement> activeDatesWebElement = genericMethod.getElements("xpath", xpath);
System.out.println("Number of Active Dates " + activeDatesWebElement.size());
// work around for an element when it is found stale
List<String> activeDateListAsString = new ArrayList<String>();
for(WebElement temp : activeDatesWebElement){
activeDateListAsString.add(temp.getText());
}
// iterate all element in the list received, which is kept in list
for(String temp : activeDateListAsString){
genericMethod.getElement("flight-departing-hp-flight", "id").click();
Thread.sleep(500);
String selectDateXpath=".//*[@id='flight-departing-wrapper-hp-flight']"
+ "/div/div/div[2]/table/tbody/tr/td/button[text()='"
+temp+"']";
genericMethod.getElement(selectDateXpath, "xpath").click();
Thread.sleep(500);
}
}
如果加载页面时元素不存在,则会出现此错误。您需要等待元素就绪:
public static Func<IWebDriver, IWebElement> Condition(By locator)
{
return (driver) => {
var element = driver.FindElements(locator).FirstOrDefault();
return element != null && element.Displayed && element.Enabled ? element : null;
};
}
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var elementU = wait.Until(Condition(By.Name("j_username")));
elementU.Click();