javascript - 选择下拉列表中标记为列表的元素

标签 javascript html selenium selenium-webdriver

我试图循环遍历下拉框内的所有元素...但是与带有值的典型 html 框不同,这些都是 UL/LI。 html 如下所示:

<ul class="ui-selectmenu-menu ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom jfpw-select ui-selectmenu-open" aria-hidden="false" role="listbox" aria-labelledby="currentStatementsDate-button" id="currentStatementsDate-menu" aria-activedescendant="currentStatementDateOptions" tabindex="0" style="width: 328px; height: 160px; float: left; overflow: hidden; outline: none; z-index: 0; top: 0px; left: 0px; position: relative; border-style: none;">
   <li role="option" tabindex="-1" aria-selected="false" id="currentStatementDateOptions" class=""><span class="ui-selectmenu-item-header">Unbilled</span></li>
   <li role="option" tabindex="-1" aria-selected="true" id="currentStatementDateOptions" class="ui-selectmenu-item-selected"><span class="ui-selectmenu-item-header">September 10, 2015</span></li>
   <li role="option" tabindex="-1" aria-selected="false" id="currentStatementDateOptions" class=""><span class="ui-selectmenu-item-header">August 12, 2015</span></li>
   <li role="option" tabindex="-1" aria-selected="false" id="currentStatementDateOptions" class=""><span class="ui-selectmenu-item-header">July 10, 2015</span></li>
   <li role="option" tabindex="-1" aria-selected="false" id="currentStatementDateOptions" class=""><span class="ui-selectmenu-item-header">June 10, 2015</span></li>
   <li role="option" tabindex="-1" aria-selected="false" id="currentStatementDateOptions" class="ui-corner-bottom"><span class="ui-selectmenu-item-header">May 12, 2015</span></li>
</ul>

我需要以某种方式选择每个列表项...但由于这些与典型的下拉列表不同,我不确定。

我猜我需要更改每次交互的属性(aria-selected)和类(所选),但不知道如何继续,因为它们都有相同的 id。

最佳答案

您想要做的是获取 LI 的集合,并循环遍历该集合,对每个集合执行 .click() (以及其他任何内容)。使用下面的代码可以轻松完成此操作。

driver.findElement(By.id("currentStatementsDate-menu")).click();
List<WebElement> options = driver.findElements(By.cssSelector("#currentStatementsDate-menu > li"));
for (WebElement option : options)
{
    option.click();
    // do something here? validations, etc.
}

CSS 选择器 #currentStatementsDate-menu > li 读取查找具有 ID (#) currentStatementsDate-menu 且具有子项 ( >) 是LI

了解更多关于CSS selectors的信息.


编辑1: 我敢打赌,您必须先单击“下拉菜单”,然后才能单击其中的元素。添加了初始点击。

关于javascript - 选择下拉列表中标记为列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684496/

相关文章:

php - 如何在 .html 文件中包含 .php 或 .html 文件?

python - 我可以使用 python、selenium 和 lxml 解析 xpath 吗?

python - Google Cloud Platform - 部署启动网络驱动程序的云函数

python - 如何检查数据库中是否创建了用户并将其删除

javascript - Vue.js 中的组件

javascript - 测试 React 组件是否已经渲染

javascript - 对对象内部数组进行排序并返回对象

javascript - Contenteditable - 如何删除带有选择文本的 html 标签

php - 防止对用户在 PHP 中提交的 HTML 内容进行 XSS 攻击,eBay 方式

javascript - 如何在不同的文件夹中调用 CSS?