问题
I'm creating List of all available elements with below Xpath.
IList<IWebElement> test= Driver.FindElements(By.XPath("//*[@id='middle-container']//div[@class='middle-section match-list']//div[contains(@class,'title')]//span[contains(text(),'" + Event.Trim() + "')]//..//..//..//..//div[contains(@class,'drop-down-content')]//table[contains(@class,'hidden-xs')]//tr//td[contains(@class,'bettype')]//a[@class='bet']`//span"));
So all the elements available in that Xpath need to be clicked. Running foreach
loop:
foreach (var item in availableSports)
{
item.Click();
}
}
My problem is let's say if test contains more than, I think, 10 elements, it is stopping the click event after around 8 to 9 clicks, and raising this error:
StaleElementReferenceException
So just wondering how can I write the method which will continue click until last available element without fail.
回答1:
You are getting StaleElementReferenceException
because something has changed in the DOM after you performed the FindElements
operation.
You have mentioned that you are clicking on the items in the list. Does this click action reload the page or navigate to a different page. In both cases the DOM has changed. Hence the Exception.
You can handle this(hopefully) with the following logic. I am a JAVA guy and the following code is in JAVA. But I think you get the idea.
IList<IWebElement> test= Driver.FindElements(By.XPath("//*[@id='middle-container']//div[@class='middle-section match-list']//div[contains(@class,'title')]//span[contains(text(),'" + Event.Trim() + "')]//..//..//..//..//div[contains(@class,'drop-down-content')]//table[contains(@class,'hidden-xs')]//tr//td[contains(@class,'bettype')]//a[@class='bet']`//span"));
// Instead of using the for each loop, get the size of the list and iterate through it
for (int i=0; i<test.length; i++) {
try {
test.get(i).click();
} catch (StaleElementReferenceException e) {
// If the exception occurs, find the elements again and click on it
test = test= Driver.FindElements(By.XPath("//*[@id='middle-container']//div[@class='middle-section match-list']//div[contains(@class,'title')]//span[contains(text(),'" + Event.Trim() + "')]//..//..//..//..//div[contains(@class,'drop-down-content')]//table[contains(@class,'hidden-xs')]//tr//td[contains(@class,'bettype')]//a[@class='bet']`//span"));
test.get(i).click();
}
}
Hope this helps you.
来源:https://stackoverflow.com/questions/33074056/selecting-multiple-elements-with-selenium