简体   繁体   中英

How can i get all list items with Selenium Webdriver?

i am new with Selenium and try to get all items in list. The code is:

<div id="books">
  <ul>
    <li>Aw</li>
    <li>Ax</li>
    <li>Ay</li>
  </ul>
</div>

I want to get all items and check all of them starts with "A"

Thanks for help.

To get all the items, we can use 'findElements' method like below:

List<WebElement> items = driver.findElements(By.xpath("//div[@id='books']/ul/li"));

Here items is a List containing the desired elements (ie all <li> elements).

We can then iterate through this list, and check if the text of these items starts with 'A':

for(WebElement e: items)
{
    System.out.print(e.getText());
    if(e.getText().startsWith("A"))
    {
        System.out.println("  ==> starts with 'A'");
    }
    else
    {
        System.out.println("  ==> does NOT start with 'A'");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM