在我的C#app中使用selenium web驱动程序我收到此错误:
OpenQA.Selenium.StaleElementReferenceException:陈旧元素 reference:元素未附加到页面文档
在此代码中:
IWebElement e = driver.FindElement(By.XPath(link_click), 10);
e.Click();
错误行在e.Click()
中,但这是一个在XPath指定的同一链接中成功执行但在最后一次尝试失败的过程!那么这个错误意味着什么以及如何解决它?
答案 0 :(得分:13)
这意味着页面中的元素已更改,或元素被删除,此链接中的完整引用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;
}
}
答案 1 :(得分:1)
当我使用其中一个网站进行日期选择时,我遇到了同样的问题。我将从日期选择器中获取所有活动(或启用)按钮,然后单击每个按钮。当我迭代元素时,它变得陈旧。我重申保留另一份清单。这可能发生了,因为一旦List获得selenium就不会将其引回。以下是固定代码
@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);
}
}
答案 2 :(得分:0)
如果加载页面时元素不存在,则会出现此错误。您需要等待元素准备就绪:
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();