Extract the list of <li>’s with xpath

Asked

Viewed 1,296 times

1

Hello,

I am developing an application with java + Selenium I have the second web element:

WebElement results = ( new WebDriverWait( driver, timeout  ) ).until( ExpectedConditions.visibilityOfElementLocated( By.id( "local" ) ) );

Where id=local is a div that contains an html list, like:

<div id="local">
<ul>
<li>
   <span>texto</span>
</li>
<li>
   <span>texto</span>
</li>
<li>
   <span>texto</span>
</li>
</ul>
</div>

I wanted to extract the text from all . I don’t know how to get the list of li’s with xpath from the div in Webelement. Then wanted to get a list in java with all the li, to iterate and thus get each span.

Any idea how to do ? I don’t know how to search with xpath the names I want.

It is possible to extract all span at once with xpath?

Thank you!

1 answer

1


Via xpath you will be able to access all spans by expression:

//div[@id = 'local']/ul/li/span

This expression says that it will enter the div with the id local go through each ul, for each ul it will go through each li and for every li he will return every span.

That said, you can do the search on selenium using the findElements and passing the By.xpath, or the way you are using you can use the visibilityOfAllElementsLocatedBy

Follow the code below:

String xPath = "//div[@id = 'local']/ul/li/span";
List<WebElement> results = (new WebDriverWait(driver, timeout))
        .until(ExpectedConditions
                .visibilityOfAllElementsLocatedBy(
                        By.xpath(xPath)
                )
);

Now in results you will have the list of all span's now if you want the list of all li's just change the xpath by deleting the /span To take the test of xpath like to use the freeformatter

  • It worked, thanks for the reply and the explanation :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.