'How to access the <li> items using Selenium webdriver

I want to access <li> items in a webpage.

From the given HTML, how can I access the list items such as User, Make & Model??

I am not able to retrieve the content of the list. My code is not executing the codes added inside the for loop.

HTML:

<li class="nav-item"> <span class="nav-link add-items" data-toggle="collapse" data-target="#add"> <i class="fas fa-plus"></i> &nbsp; Add</span>
  <ul class="add-menu collapse" id="add">
    <li><span data-toggle="modal" data-target="#add-user-modal">User</span></li>
    <li><span data-toggle="modal" data-target="#add-make-modal">Make</span></li>
    <li><span data-toggle="modal" data-target="#add-model-modal">Model</span></li>
  </ul>
</li>


Solution 1:[1]

To match a single item you can use the following XPath locator :

//li/span[text()='User']

enter image description here

To match all items and get their text the relevant XPath Expression would be:

//ul[@class='add-menu collapse']/li/span

Example Python code:

for li in driver.find_elements_by_xpath("//ul[@class='add-menu collapse']/li/span"):
    print(li.text)

Solution 2:[2]

To print the list items such as User, Make & Model you can use the following solution:

  • Java:

    • Using cssSelector:

      List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li.nav-item ul.add-menu.collapse li>span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
      System.out.println(myItems);
      
    • Using xpath:

      List<String> myItems = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span"))).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList());
      System.out.println(myItems);
      
  • Python:

    • Using CSS_SELECTOR:

      print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.nav-item ul.add-menu.collapse li>span")))])
      
    • Using XPATH:

      print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='nav-item']//ul[@class='add-menu collapse']//li/span")))])
      
    • Note : You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitri T
Solution 2 undetected Selenium