How to find child (not all descendants) elements through an existing element (not xpath)

I am trying to find the children of an already found item. The problem I am facing is that I can only show all the descendants of an existing element.

For example, given the following HTML snippet (you can recognize this as a drop-down menu for the bootstrap).

<div class="dropdown"> <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu"> <li> <a tabindex="-1" href="#">Action</a> </li> <li> <a tabindex="-1" href="#">Another action</a> </li> <li> <a tabindex="-1" href="#">Something else here</a> </li> <li class="divider"></li> <li class="dropdown-submenu"> <a tabindex="-1" href="#">More options</a> <ul class="dropdown-menu"> <li><a tabindex="-1" href="#">Second level link</a></li> <li><a tabindex="-1" href="#">Second level link</a></li> <li><a tabindex="-1" href="#">Second level link</a></li> <li><a tabindex="-1" href="#">Second level link</a></li> <li><a tabindex="-1" href="#">Second level link</a></li> </ul> </li> </ul> </div> 

I already have an existing WebElement in the dropdown menu

 WebElement dropdown = driver.findElementBy(By.cssSelector(".dropdown > .dropdown-menu"); 

And I'm trying to get a handle for all children of an external menu. I originally did the following

 List<WebElement> menuItems = dropdown.findElements(By.cssSelector(" > li > a"); 

provided that this leads to the creation of the final selector

 .dropdown > .dropdown-menu > li > a 

However, this raises an exception.

 Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: An invalid or illegal string was specified 

Doing the following does not throw an exception, but returns all descendants ... not just children. The menu items involved are 10 instead of 5.

 List<WebElement> menuItems = dropdown.findElements(By.cssSelector("li > a"); 

So, I think my last question is how to use By.cssSelector to get only direct children of an already found node?

XPATH is not a valid solution.

+4
source share
2 answers

How about a little logic change?

You have a WebElement called dropdown , but it is defined as the dropdown-menu class in the DOM. Why not define dropdown as div.dropdown instead of ul.dropdown-menu ? Then your problem can be solved.

 WebElement dropdown = driver.findElement(By.cssSelector(".dropdown"); List<WebElement> menuItems = dropdown.findElements(By.cssSelector(".dropdown-menu[role='menu'] > li > a"); List<WebElement> subMenuItems = dropdown.findElements(By.cssSelector(".dropdown-submenu li > a"); 
+1
source

Why not just combine them?

 List<WebElement> menuItems = driver.findElements(By.cssSelector(".dropdown > .dropdown-menu > li > a"); 
0
source

Source: https://habr.com/ru/post/1495395/


All Articles