简体   繁体   English

如何访问 <li> 使用Selenium webdriver的项目

[英]How to access the <li> items using Selenium webdriver

I want to access <li> items in a webpage. 我想访问网页中的<li>项目。

From the given HTML, how can I access the list items such as User, Make & Model?? 从给定的HTML,我如何访问列表项,如用户,制作和模型?

I am not able to retrieve the content of the list. 我无法检索列表的内容。 My code is not executing the codes added inside the for loop. 我的代码没有执行for循环中添加的代码。

HTML: 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 : 要匹配单个项目,您可以使用以下XPath定位器:

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

在此输入图像描述

To match all items and get their text the relevant XPath Expression would be: 要匹配所有项目并获取其文本,相关的XPath表达式将是:

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

Example Python code: 示例Python代码:

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 : Java

    • Using cssSelector : 使用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 : 使用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 : Python

    • Using CSS_SELECTOR : 使用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 : 使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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