[英]How to click on multiple checkboxes based on value through Selenium and Java
I am trying to select multiple checkboxes.我正在尝试选择多个复选框。 Here is my HTML这是我的 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>
I want to select only two checkbox.我只想选择两个复选框。 I'm doing this:我这样做:
driver.findElement(By.xpath("//input[@type='checkbox' && @name='permissions' && @value='"+value+'"")).click();
here id tag is generated randomly.这里 id 标签是随机生成的。 How to select multiple checkboxes based on the value tag?如何根据值标签选择多个复选框?
By Using string array I did this.通过使用字符串数组,我做到了。 Please try.请尝试。
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();
}
Or或者
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);
}
To click on any of the check boxes you can create a function as follows:要单击任何复选框,您可以创建一个函数,如下所示:
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();
}
Now you can call the function from anywhere within your program as:现在您可以从程序中的任何位置调用该函数,如下所示:
locateClickCheckbox("Add/Update Network Security")
locateClickCheckbox("Create User")
locateClickCheckbox("Create Project")
locateClickCheckbox("Update User Details")
locateClickCheckbox("View User")
locateClickCheckbox("Assign Permissions")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.