我有一个项目,其中隐藏了 native 下拉菜单并使用了自定义下拉菜单。因此,我无法使用 selenium select 方法(选择和选项是隐藏的且不可用)。所有下拉菜单(称呼、国家/地区、出生日期等)均作为自定义下拉菜单实现。
<div class="medium-8 large-4 left column">
<select name="register[personal][salutation]" id="register_personal_salutation" style="display: none;">
<option value="mr">Herr</option>
<option value="ms">Frau</option>
</select>
<div class="select-dropdown">
<div class="selected">Herr</div>
<div class="choices">
<ul>
<li>Herr</li>
<li>Frau</li>
</ul>
</div>
</div>
</div>
解决方案 1(不太好):单击“select-dropdown”并单击选项。它可以工作,但不可重复使用。
解决方案 2(首选):实现一个自己的可重用“customSelect”方法,以便我可以通过给定的选择器和选项字符串(如 webdriver select)选择正确的选项。但我不知道如何实现这样的功能。有人已经使用过自定义下拉菜单并有解决方案或技巧吗?
最佳答案
好的,这是我的解决方案。 “optionClass”是选项的CSS选择器,“option”是应该选择的值。我认为这不是最好的解决方案,而是解决问题的一种方法。有任何反馈、改进或想法吗?
public void customSelect(String optionClass, String option) {
log.trace("I custom select the option " + option + " from the dropdown");
int amountOptions = this.getNumOfElements(By.cssSelector(optionClass));
for (int pos = 1; pos <= amountOptions; pos++) {
String sortOption = this.getText(By.cssSelector(optionClass + ":nth-child(" + pos + ")"));
if (sortOption.equalsIgnoreCase(option)) {
this.click(By.cssSelector(optionClass + ":nth-child(" + pos + ")"));
return;
}
}
throw new NoSuchElementException("The dropdown does not contain the option " + option
+ " and therefore it is not possible to select it.");
}
关于java - 如何使用selenium选择自定义下拉列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32926464/