我遇到了一个非常类似的问题:Selenium: find element "next to" other element
我的元素如下所示:
<div class="a-Trinity has-left-widget has-right-widget" style="cursor: pointer;">
<div class="trinity-left-widget" style="">
<div>
<span class="layer-style-rule-slice" style="background-color: rgb(233, 34, 91); border-color: rgb(255, 255, 255); margin-top: 12px;"></span>
<span class="layer-style-rule-slice" style="background-color: rgb(75, 170, 234); border-color: rgb(255, 255, 255); margin-top: 6px;"></span>
<span class="layer-style-rule-slice" style="background-color: rgb(42, 200, 159); border-color: rgb(255, 255, 255); margin-top: 0px;"></span>
<span class="layer-style-rule-slice" style="background-color: rgb(153, 207, 34); border-color: rgb(255, 255, 255); margin-top: -6px;"></span>
<span class="layer-style-rule-slice" style="background-color: rgb(247, 151, 29); border-color: rgb(255, 255, 255); margin-top: -12px;"></span>
</div>
</div>
<div class="gwt-Label trinity-middle-widget form-text">Street Lights</div>
<div class="trinity-right-widget" style="">
<div class="small-switch-container layer-right-switch">
<div class="small-switch switch-active">
<div class="small-switch-button"></div>
</div>
</div>
</div>
我想检查是否显示了switch-active。我正在使用以下内容找到正确的元素:
String className = "gwt-Label trinity-middle-widget form-text";
String htmlElement = "div";
String textToFind = layerName; // i.e. Street Light
List<WebElement> elements = Common.findElementsUsingHtmlXpathClass(driver, htmlElement, className);
Common.myPrint(thisClass + " elements count: " + elements.size());
for (WebElement element : elements) {
// select an element
String text = Common.getAllAttributes(element, driver);
if (text != null) {
text = text.trim();
if (text.contains(textToFind)) {
// so this is my element
// here is where I need to get the next one
}
}
}
findElementsUsingHtmlXpathClass的代码:
public static List<WebElement> findElementsUsingHtmlXpathClass(WebDriver driver, String htmlElement,
String className) {
List<WebElement> elements = driver
.findElements(By.xpath("//" + htmlElement + "[contains(@class, '" + className + "')]"));
return elements;
}
我无法看到如何应用引用文章中给出的解决方案,因为我没有可以通过ID找到的元素。
如何获得下一个元素?
来自cruisepandey的这个解决方案。我只是改变了方法的名称来反映它的新功能:
public static List<WebElement> findElementsFollowingHtmlXpathClass(WebDriver driver, String htmlElement,
String className) {
List<WebElement> elements = driver
.findElements(By.xpath("//" + htmlElement + "[contains(@class, '" + className + "')]/following-sibling::div[@class='trinity-right-widget']/descendant::div[contains(@class,'switch-active')]"));
return elements;
}
答案 0 :(得分:1)
你可以像这样使用它:
public static List<WebElement> findElementsUsingHtmlXpathClass(WebDriver driver, String htmlElement,
String className) {
List<WebElement> elements = driver
.findElements(By.xpath("//" + htmlElement + "[contains(@class, '" + className + "')]/following-sibling::div[@class='trinity-right-widget']/descendant::div[contains(@class,'switch-active')]"));
return elements;
}