ByChained是一个存储By数组的类,和ByAll的区别就是ByChained能够把子元素也存储起来。
ByChained应该也是可以实现远程测试的。
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ByChained extends By implements Serializable {
private static final long serialVersionUID = 1563769051170172451L;
private By[] bys;
public ByChained(By... bys) {
this.bys = bys;
}
@Override
public WebElement findElement(SearchContext context) {
List<WebElement> elements = findElements(context);
if (elements.isEmpty())
throw new NoSuchElementException("Cannot locate an element using " + toString());
return elements.get(0);
}
@Override
public List<WebElement> findElements(SearchContext context) {
if (bys.length == 0) {
return new ArrayList<>();
}
List<WebElement> elems = null;
for (By by : bys) {
List<WebElement> newElems = new ArrayList<>();
if (elems == null) {
newElems.addAll(by.findElements(context));
} else {
for (WebElement elem : elems) {
newElems.addAll(elem.findElements(by));
}
}
elems = newElems;
}
return elems;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("By.chained(");
stringBuilder.append("{");
boolean first = true;
for (By by : bys) {
stringBuilder.append((first ? "" : ",")).append(by);
first = false;
}
stringBuilder.append("})");
return stringBuilder.toString();
}
}