【问题标题】:Why doesn’t my code reliably click on the dropdown menu item?为什么我的代码不能可靠地单击下拉菜单项?
【发布时间】:2017-02-17 17:36:32
【问题描述】:

为什么我的代码不能可靠地点击下拉菜单项?

  1. 我的代码不能可靠地单击预期的下拉菜单项。
  2. 例如,如果我执行相同的测试 100 次,则有 12 个测试将失败,因为该方法不会选择预期的菜单项,比如说(先生),即使使用发送键也会出现同样的问题。
  3. 我设置了 x30 秒等待元素可见的等待时间,即使等待元素可点击也会出现同样的问题。
  4. 例如请看下面的下拉项:

    <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>
    

  5. 我的代码由以下内容构成:

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

    }

【问题讨论】:

标签: java selenium selenium-webdriver webdriver


【解决方案1】:

您需要在下拉菜单而不是选项上创建选择对象。此外,您不需要任何 for 循环。

List<WebElement> options = dropdown.findElements(By.Id("titlefield"));
Select selectDropdown = new Select(dropdown);
selectDropdown.selectByVisibleText(textToSearchFor);

【讨论】:

  • 感谢您的评论,如果列表项仅引用选择项,列表项将如何存储列表的值?
  • @Phil_P85 我没有 webdriver API 的内部,但这就是它的工作原理。
【解决方案2】:

你也可以试试这个:
Select selectDropdown = new Select(driver.findElement(By.id("titlefield"))); selectDropdown.selectByVisibleText(textToSearchFor);

【讨论】:

  • selectDropdown.selectByVisibleText("textToSearchFor"); -- textToSearchFor 不应使用双引号...否则 selenium 将搜索此字符串而不是变量 textToSearchFor 的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2014-11-22
相关资源
最近更新 更多