Home > Enterprise >  How find all items on the header section on WebSite?
How find all items on the header section on WebSite?

Time:11-09

I have this code:

<ul class="sidebar-menu left">
    <li index="1">Apple</li>
    <li index="2">Orange</li>
    <li index="3">Banana</li>
</ul>

How can I add this list(all li) to List<WebElement.>?

CodePudding user response:

To print all the header section texts you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy() and you can use Java8 stream() and map() and you can use either of the following Locator Strategies:

  • Using cssSelector and getText():

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("ul.sidebar-menu.left li"))).stream().map(element->element.getText()).collect(Collectors.toList()));
    
  • Using xpath and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//ul[@class='sidebar-menu left']//li"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
    

CodePudding user response:

You can use findElements method.

    ArrayList<String> fruitNames = new ArrayList<String>();
    List<WebElement> fruits = driver
            .findElements(By.xpath("//ul[contains(@class,'sidebar-menu left')]//child::li[@index]"));

    for (WebElement element : fruits) {
        fruitNames.add(element.getText());
    }

CodePudding user response:

If this class is unique

sidebar-menu left

then you can construct this

  1. cssSelector

    ul.sidebar-menu.left li
    
  2. xpath

    //ul[contains(@class,'sidebar-menu left')]//child::li[@index]
    

child is just specification, you can remove that as well

//ul[contains(@class,'sidebar-menu left')]//li[@index]

They should represent multiple node in HTMLDOM, in this example it would be 3.

to add to list of web element, simply use findElements (plural)

List<WebElement> elems = driver.findElements(By.xpath("//ul[contains(@class,'sidebar-menu left')]//child::li[@index]"));

In case you want to retrieve web element text,

for (WebElement e : elems){
       e.getText();
    }

CodePudding user response:

Use findElements by xpath with

xpath = "//ul[@class ='sidebar-menu left']//li"
  • Related