如何使用硒迭代单击下拉列表中的所有元素

时间:2019-07-17 21:15:26

标签: selenium selector dropdown

我正在使用elenium和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
}

当我在调试模式下运行代码时,我期望变量“ dropdown”不为空

3 个答案:

答案 0 :(得分:0)

对于xpath,为什么不直接使用:

 //div[@class='dropdown-menu shadow px-4 show']//label ---yields 6 rows

如果这不起作用,请确保下拉菜单不在iframe中。您需要添加// //标签,以便所有元素都出现在“ FindElements”中。没有它,您的回报是1。

答案 1 :(得分:0)

请尝试使用以下xpath。可能是因为树皮,

// div [包含(@class,'下拉菜单')] //标签

答案 2 :(得分:0)

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

//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();

}

希望它会有所帮助:)