用硒选择多个元素 [英] Selecting multiple elements with Selenium

查看:257
本文介绍了用硒选择多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Xpath下方创建所有可用元素的列表.

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"));

因此,需要单击该Xpath中所有可用的元素.运行foreach循环:

So all the elements available in that Xpath need to be clicked. Running foreach loop:

foreach (var item in availableSports)
    {
        item.Click();        
    }
}

我的问题是,假设测试包含10个以上的元素,它会在大约8到9次点击后停止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.

推荐答案

执行FindElements操作后,由于DOM中的某些更改,您将获得StaleElementReferenceException.

You are getting StaleElementReferenceException because something has changed in the DOM after you performed the FindElements operation.

您提到您正在单击列表中的项目.此点击操作是否重新加载页面或导航至其他页面.在这两种情况下,DOM均已更改.因此是例外.

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.

您可以按照以下逻辑处理(希望)此操作.我是一个Java专家,下面的代码在JAVA中.但是我想你明白了.

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();
    }
}

希望这对您有所帮助.

这篇关于用硒选择多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆