Selecting multiple elements with Selenium

99封情书 提交于 2019-12-12 16:54:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!