java - Selenium WebDriver:如何在跨度下拉列表中选择一个值?
问题描述
我正在尝试让我的 Selenium 脚本单击下拉菜单中的值。但是,在我最初单击下拉列表后,我无法在下拉列表中执行任何操作。我在网上查看过,只有当下拉菜单是“选择”时才能找到答案。
这是下拉列表的 HTML:
<span class="select2-selection__rendered" title="1st item"
id="select2-id_template_or_inspection-container">
</span>
这是我单击下拉列表的代码片段:
//Choose a Template from Dropdown
WebElement dropdownBtn = webDriver.findElement(
By.id("select2-id_template_or_inspection-container"));
dropdownBtn.click();
这是我尝试单击下拉列表中的值的代码片段:
WebElement dropdownItemBtn = webDriver
.findElement(By.id("select2-id_template_or_inspection-result-hlwt-tmpl-2583"));
dropdownItemBtn.click();
但是,每次重新加载页面时,下拉列表中值的 ID 都会更改。
感谢您的帮助!
解决方案
您可以尝试这种方法:
这就是您所做的,单击 span 以显示其下拉项
//Choose a Template from Dropdown WebElement dropdownBtn = webDriver.findElement(By.id("select2-id_template_or_inspection-container")); dropdownBtn.click();
因为每次重新加载页面时下拉列表中的值的 ID 都会更改,因此您可以使用
dropdownBtn
它来查找其子项/子项作为下拉项,然后单击所需的下拉列表:List<WebElement> dropdownItems = dropdownBtn.findElements(By.tagName("tagNameOfDropdownItems")); dropdownItems.get(0).click(); // click on first Dropdown, for example
因为 ID 是动态变化的,所以让我们尝试通过tagName
. 希望能帮助到你。
推荐阅读
- haskell - 你能在 Haskell 类型签名中编写参数化类型吗?
- c - Luhn 的校验和算法在 C 中的解决方案
- reactjs - 如何使用 Firebase Auth 的 useEffect 清理功能取消所有订阅和异步任务
- java - 如何在java(Android)中将对象(在这种情况下为数组列表)从一个片段发送到另一个片段
- r - ggplot facet 中缺少 2D 密度层
- powerbi - Dax 函数 DATESINPERIOD 未给出正确答案
- css - 如何通过css缩小图像?
- vulkan - VkSubpassDependency 规范说明
- javascript - 从函数返回到绑定的Angular模板文字中的换行符?
- javascript - 如何通过 node-fetch 发送 cookie