Webdriver语言 - 查找具有相同类的前 x 个元素



有人可以帮助我解决以下问题: 我有很多li元素的页面,如下所示:

<ul class="feed-tips" id="Grid" data-sport="" data-country="" data-league="">
<li class="feed-item vevent tip-list-row" data-sort-bookmaker="12" data-sort-datetime="1525849200" data-sort-match="1" data-sort-odds="1.80" data-sort-rating="3" data-sort-status="1" data-sort-yield="-2.106" data-tip-id="6900510">
<li class="feed-item vevent tip-list-row" data-sort-bookmaker="22" data-sort-datetime="1525852800" data-sort-match="2" data-sort-odds="2.59" data-sort-rating="2" data-sort-status="1" data-sort-yield="-3.082" data-tip-id="6900483">
<li class="feed-item vevent tip-list-row" data-sort-bookmaker="22" data-sort-datetime="1525852800" data-sort-match="3" data-sort-odds="2.21" data-sort-rating="2" data-sort-status="1" data-sort-yield="-4.118" data-tip-id="6899865">

在该li列表中,每个元素都有以下类:

<span class="original-language-image flag-icon flag-icon-gb"</span>

所有li元素都有该跨度类,唯一的区别是上面显示的-gb,它是不同的国家/地区代码。

我必须找到具有相同gb代码的前n 个元素(而且这些元素必须一个接一个(,并比较是否与第一个元素相同。休息用不同的代码,我不需要。

尝试使用以下代码,但做错了(或在if语句中使用等号犯了错误(:

List<WebElement> tipsGB = driver.findElements(By.xpath("//ul[@class='feed-tips']/li/div[@class='author medium-3 small-12 column padding-reset tip-list-row__author']n"
+ "//div[@class='original-tip-language-container']/span[contains(@class,'flag-icon-gb')]"));
WebElement firstTip = tipsGB.get(0);
for (int p = 1; p < tipsGB.size(); p++) {
System.out.println(tipsGB.get(p));
WebElement nextTip = tipsGB.get(p);
if (nextTip.equals(firstTip)) {
WebElement tipLink = nextTip.findElement(By.xpath("../../../..n"
+ "/div[@class='tip medium-9 small-12 column padding-reset dtstart tip-list-row__tip']n"
+ "/div[@class='tip-match medium-12 column']/div[@class='tip-teams']/a"));
System.out.println("Link to a tip with same language is: " + tipLink.getAttribute("href"));
} else {
System.out.println("No more tips in same language on top of page");
continue;
}
}

提前谢谢你

尝试以下方案:

1.选择其类包含术语"flag-icon-gb">的所有元素。(您可以通过替换上面的 * 将搜索限制为一种元素。 例如,要搜索所有 li,您可以输入//li[...]

2. 遍历您的列表以操作您想要的前n 个元素。

3.对循环中的每个元素做你想做的事(比较、获取子元素、点击等,...(

//Get all flags containing GB
List<WebElement> tipsGB = driver.findElements((By.xpath("//*[contains(@class,'flag-icon-gb')]"))
//Iterate over the list and do your stuff
for(int i=0; i<numberofElementsYouWant<;i++){
Webelement currentElement = tipsGB.get(i);
//manipulate your elements here
currentElement.Dostuff();
}

编辑 :看来您的问题与比较有关。 您正在尝试比较对象(WebElements(,而这些对象并不相等。只有他们的文本是。 尝试这样:

String firstTip = tipsGB.get(0).getAttribute("data-tip-id");

在循环中做同样的事情,然后比较

String nextTip = tipsGB.get(p).getAttribute("data-tip-id");
if (nextTip.equals(firstTip)) {
....
}

最新更新