[英]Why doesn’t my code reliably click on the dropdown menu item?
Why doesn't my code reliably click on the dropdown menu item? 为什么我的代码不能可靠地点击下拉菜单项?
For example please see the following dropwdown item: 例如,请参阅以下dropwdown项:
<select id="titlefield" class="form-control ng-pristine ng-untouched ng-invalid ng-invalid-required" name="Salutation" ng-model="PersonalDetails.Salutation" ng-options="salut.id as salut.id for salut in Salutations" ng-required="FlowData.IsGuest" required="required"> <option class="ng-binding" value="">Please select</option> <option value="0" label="Mr.">Mr.</option> <option value="1" label="Miss">Miss</option> <option value="2" label="Mrs.">Mrs.</option> <option value="3" label="Ms.">Ms.</option> <option value="4" label="Dr.">Dr.</option>
My code is constructed of the following: 我的代码由以下构造:
public void selectTitleFromDropdownMenu(WebElement dropdown, String textToSearchFor) { Wait<WebDriver> tempWait = new WebDriverWait(this.driver, 30); try { tempWait.until(ExpectedConditions.visibilityOf(dropdown)); List<WebElement> options = dropdown.findElements(By.tagName("option")); Select selectDropdown = new Select(dropdown); for (int i = 0; i < options.size(); i++) { if (options.get(i).getText().equals(textToSearchFor)) { selectDropdown.selectByVisibleText(textToSearchFor); System.out.println("Successfully selected the following text: " + textToSearchFor + ", using the following webelement: " + "<" + dropdown.toString() + ">"); } } }catch(Exception e) { System.out.println("Unable to select the following text: " + textToSearchFor + ", using the following WebElement: " + "<" + dropdown.toString() + ">"); Assert.assertFalse(true, "Unable to select the required text from the dropdown menu, Exception: " + e.getMessage()); }
} }
You need to create the select object on dropdown and not on options. 您需要在下拉列表中创建选择对象,而不是在选项上创建。 Also, you don't need any for loop. 此外,您不需要任何for循环。
List<WebElement> options = dropdown.findElements(By.Id("titlefield"));
Select selectDropdown = new Select(dropdown);
selectDropdown.selectByVisibleText(textToSearchFor);
你也可以试试这个:
Select selectDropdown = new Select(driver.findElement(By.id("titlefield"))); selectDropdown.selectByVisibleText(textToSearchFor);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.