例如,某些html有几个具有css路径table.class1.class2[role="menu"]的元素,但是在任何给定时间仅这些元素之一是可见的,因此我想只获得一个可见的元素。
我可以调整CSS路径以缩小范围吗?

最佳答案

可能使用Linq来获取列表。我不确定您使用的是哪种语言。但是,可以使用其中任何一种来应用类似的概念。使用Linq
C#中完成这种情况非常简单

public IWebElement Test()
{
    //selector
    By bycss = By.CssSelector("table.class1.class2[role='menu']");

    return Driver.FindElements(bycss).ToList().FirstOrDefault(d => d.Displayed);
}


并且,请确保导入
using System.Linq;(如果使用的是C#

在Java中,您可以执行以下操作(不使用lambdas)

List<WebElement> visibleList = null;
//selector
By byCss = By.cssSelector("table.class1.class2[role='menu']");
//list of visible and hidden elements
Iterator<WebElement> iterator = driver.findElements(byCss).iterator();

while (iterator.hasNext()){
    WebElement element = iterator.next();
 if (element.isDisplayed()){
     //building the list of visible elements
     visibleList.add(element);
 }
}

//get the first item of the list
//you can return all if needed
return visibleList.get(0);

09-16 06:44
查看更多