TomasMaplewood
TomasMaplewood

Reputation: 1

How find all items on the header section on WebSite?

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.>?

Upvotes: 0

Views: 114

Answers (4)

Frenchy
Frenchy

Reputation: 17037

Use findElements by xpath with

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

Upvotes: 0

cruisepandey
cruisepandey

Reputation: 29372

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();
    }

Upvotes: 0

Nandan A
Nandan A

Reputation: 2922

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());
    }

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193298

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()));
    

Upvotes: 1

Related Questions