【问题标题】:button dropdown automation in selenium硒中的按钮下拉自动化
【发布时间】:2015-12-21 22:51:27
【问题描述】:

如何在以下示例代码中自动选择下拉值:

<div class="dropdown">
  <button id="dropdown-button-1" class="dropdown-toggle btn btn-default-alt" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Button Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdown-button-1">
    <li role="presentation">
      <a href="http://www.google.com" role="menuitem">Google</a>
    </li>
    <li class="divider mvn"></li>
    <li role="presentation">
      <a href="http://www.yahoo.com" role="menuitem">Yahoo</a>
    </li>
    <li class="divider mvn"></li>
    </li><li role="presentation">
      <a href="http://www.aol.com" role="menuitem">Aol</a>
    </li>
  </ul>
</div>

选择显然不起作用,因为这不是常规的下拉菜单,selenium 将此元素检测为按钮。

【问题讨论】:

    标签: selenium


    【解决方案1】:

    如何使用驱动程序点击和等待? 我就是这样处理的。

    WebElement button = driver.findElement(By.id("dropdown-button-1"));
    button.click();
    WebElement we = new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@aria-labelledby='dropdown-button-1']")));
    By pathOfSelection = By.xpath("./li[@role='presentation']/a[text()='Google']"); // if you need to select options other than Google, you can change the text to any of the options.
    WebElement option = null;
    try {
       option = we.findElement(pathOfSelection);
    } catch(NoSuchElementException e){
       System.out.println("No such option. " + e.getMessage);
       throw e;
    }
    option.click();
    

    您可以通过在按钮上执行 getText 来验证是否选择了正确的元素。

    if(!"Google".equals(button.getText())) {
        throw new Exception("Incorrect option selected");
    }
    

    【讨论】:

      【解决方案2】:

      尝试使用操作。如需更多参考,请访问:https://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html

      这里是示例代码:

      Actions actions = new Actions(driver);
      WebElement abc = driver.findElement(By.xpath("xpath of drop down"));
      actions.moveToElement(abc);
      actions.moveToElement(driver.findElement(By.id("desired option"))).click().perform();
      

      注意:你也可以使用 xpath 移动到元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        • 2016-11-05
        • 1970-01-01
        • 2010-12-24
        • 1970-01-01
        相关资源
        最近更新 更多