我想访问网页中的
<li>
项目。
从给定的 HTML 中,我如何访问用户、品牌和型号等列表项??
我无法检索列表的内容。我的代码没有执行在 for 循环中添加的代码。
HTML:
<li class="nav-item"> <span class="nav-link add-items" data-toggle="collapse" data-target="#add"> <i class="fas fa-plus"></i> 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>
要打印 User、Make & Model 等列表项,您可以使用以下解决方案:
Java:
使用
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);
使用
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:
使用
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")))])
使用
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")))])
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC