简体   繁体   中英

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>

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

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

在此输入图像描述

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)

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 

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