如何通过Selenium和Java基于值单击多个复选框

时间:2019-02-09 15:31:06

标签: java selenium selenium-webdriver xpath xpath-1.0

我正在尝试选择多个复选框。这是我的HTML

<div class="col-md-6">
   <div class="form-sections">
      <ul>
         <li>Select permissions</li>
         <li><input type="checkbox" id="permissions1549733530963" name="permissions"><label for="permissions1549733530963">Select all</label></li>
      </ul>
      <div class="searchbox-container">
         <div class="check-list">
            <ul>
               <li><input type="checkbox" id="371549733530963" name="permissions" value="Add User"><label for="371549733530963">Add User</label></li>
               <li><input type="checkbox" id="31549733530965" name="permissions" value="View User"><label for="31549733530965">View User</label></li>
            </ul>
         </div>
      </div>
   </div>
</div>

我只选择两个复选框。我正在这样做:

driver.findElement(By.xpath("//input[@type='checkbox' && @name='permissions' && @value='"+value+'"")).click();

此处id标签是随机生成的。如何根据值标签选择多个复选框?

2 个答案:

答案 0 :(得分:1)

通过使用字符串数组,我做到了。请尝试。

String[] users = {"Add/Update Network Security", "Create User"};
     int size = users.length;
        for (int i=0; i<size; i++)
        {
           String value=users[i];
           System.out.println(value);

           WebDriverWait wait = new WebDriverWait(driver, 30);
           wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@type='checkbox' and @value='" +value +"']"))).click();


        }

String[] users = {"Add/Update Network Security", "Create User"};
         int size = users.length;
            for (int i=0; i<size; i++)
            {
               String value=users[i];
               System.out.println(value);
               WebElement element=driver.findElement(By.xpath("//input[@type='checkbox' and @value='" +value +"']"));
               JavascriptExecutor js = (JavascriptExecutor) driver;
               js.executeScript("arguments[0].click();", element);                           

            }

答案 1 :(得分:0)

要单击任何复选框,您可以创建如下功能:

if executor has run for <= 1s stop launching thread  
if executor has run for > 1s and < 3s. Start and keep launching thread 
if executor has run for < 3s stop launching thread.

现在,您可以在程序中的任何位置调用该函数,如下所示:

public void locateClickCheckbox(String item)
{
    String myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='form-sections']//div[@class='check-list']//li/input[@value='" + item + "']"))).getAttribute("id");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='form-sections']//div[@class='check-list']//li/label[@for='" + myElement + "']"))).click();
}