按钮下拉 - 如何使用带有java的webdriver选择项目

时间:2017-11-15 09:33:56

标签: java xpath selenium-webdriver angularjs-ng-repeat

我有一个带下拉项目的按钮, 如果我点击按钮,它会打开列表并选择项目 下面是html

<button id="btn-append-to-body" class="btn btn-primary mobile-quick-button dropdown-toggle" type="button" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false">
<div class="clearfix">
<span class="pull-left text-left ng-binding" tabindex="0">   Select one </span>
<span class="pull-right text-right ng-binding">
</div>
</button>
<ul class="uib-dropdown-menu dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<!-- ngRepeat: option in dropOptions -->
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0" style="">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">frame number</span>
</div>
</a>
</li>
<!-- end ngRepeat: option in dropOptions -->
<li id="quickOption" class="ng-scope" role="presentation" name="quickOption" ng-repeat="option in dropOptions" ng-click="selectOption(option)" required="" tabindex="0">
<a href="">
<div class="clearfix">
<span class="pull-left ng-binding">serial number</span>
</div>
</a>
</li>
</ul>

我想从此列表中选择任何一项,

public void lookupSearch (String item){
driver.findElement(By.xpath("//*[@id='btn-append-to-body']")).click();
//then i choose/click the parameter item (i.e frame number or serial number)
}

将项目作为参数传递

请指导我如何选择项目

2 个答案:

答案 0 :(得分:1)

要点击带有下拉项的按钮并从该列表中选择任何一项,您可以使用以下代码块:

public void lookupSearch (String item)
{
    driver.findElement(By.xpath("//button[@id='btn-append-to-body']/div/span[contains(.,'Select one')]")).click();
    WebDriverWait wait4elements = new WebDriverWait(driver, 10);
    List<WebElement> myElements = wait4elements.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//ul[@class='uib-dropdown-menu dropdown-menu']/li/a/div/span"), 2));
    for(WebElement elem:myElements)
        if(elem.getAttribute("innerHTML").contains(item))
        {
            elem.click();
            break;
        }
    System.out.println("Element with text as "+ item +" is selected");
}

答案 1 :(得分:0)

下面是ul的答案,找到李计数,然后得到每个li文本并与item字符串进行比较

WebElement uList = driver.findElement(By.xpath("//*[@id='quick-search-dropdown']/ul"));
            List<WebElement> listCount = uList.findElements(By.tagName("li"));
            for (int i = 1; i <= listCount.size(); i++) {
                WebElement lookupItem = driver.findElement(By.xpath("(//li[@id='quickOption']/a/div/span[1])[" + i + "]"));
                String lookupItemValue = lookupItem.getText();
                if (lookupItemValue.equalsIgnoreCase(Item)) {
                    lookupItem.click();
                }
            }