首页 > 解决方案 > 如何使用硒迭代地单击下拉列表中的所有元素?

问题描述

我正在使用 selenium 和 C# 自动化框架测试 react.js 前端 Web 应用程序,我需要单击下拉列表中的所有元素,理想情况下,我想选择下拉列表作为元素列表,并遍历每个元素并单击它。

我试图通过 Xpath、Cssselector、cssName 找到下拉菜单,但似乎都不起作用,当我调试代码时,我的“dropDown”变量始终为空

这是下拉菜单的代码

<div class="dropdown-menu shadow px-4 show">
  <div>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="1">1 </label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="2">2</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox"value="3">3</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="4">4</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="5">5</label>
        <label class="dropdown-item m-0 px-0 d-block"><input type="checkbox" value="6">6</label>
      </div>
</div>

这是我的硒代码

public static IList<IWebElement> dropDownClick (IWebDriver _driver) {
  IList<IWebElement> dropdown = _driver.FindElements (By.ClassName ("dropdown-menu shadow px-4 show"));
  return dropdown
}

当我在调试模式下运行代码时,我预计变量“下拉列表”不为空

标签: seleniumselectordropdown

解决方案


请使用下面编写的代码来获取元素并单击迭代中的每个元素:

//Below line Finds the dropdown 
WebElement dropdownElement = driver.findElements(By.xpath("//div[contains(@class,'dropdown-menu')]"));

//Below line stores all elements present in dropdown in a list of webelements
List<WebElement> elements = driver.findElements(By.xpath("//div[contains(@class,'dropdown-menu')]//label"));

for(WebElement ele : elements){
    //To click on dropdown
    dropdownElement.click();

    //To click on label present in dropdown. This will change with each Iteration
    ele.click();

}

希望能帮助到你 :)


推荐阅读