首页 > 解决方案 > 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 都会更改。

感谢您的帮助!

标签: javahtmlselenium

解决方案


您可以尝试这种方法:

  1. 这就是您所做的,单击 span 以显示其下拉项

    //Choose a Template from Dropdown
    
    WebElement dropdownBtn = webDriver.findElement(By.id("select2-id_template_or_inspection-container"));
    dropdownBtn.click();
    
  2. 因为每次重新加载页面时下拉列表中的值的 ID 都会更改,因此您可以使用dropdownBtn它来查找其子项/子项作为下拉项,然后单击所需的下拉列表:

    List<WebElement> dropdownItems = dropdownBtn.findElements(By.tagName("tagNameOfDropdownItems"));
    dropdownItems.get(0).click(); // click on first Dropdown, for example
    

因为 ID 是动态变化的,所以让我们尝试通过tagName. 希望能帮助到你。


推荐阅读