问题
M unable to validate checkbox, if it's selected or not because both the HTML are same
I tried isSelected(), but it's not working
Below is the HTML code for both selected and unselected
1) Selected
<label class="c-account-access-panel__checkbox " for="23336" data-js-checkbox-label="">
<input id="23336" class="c-account-access-panel__checkbox-input" type="checkbox"
data-label-for-value-missing="Please select at least one account from the options below" data-form-field-validation-on-grid=""
required="" checked="" data-js-checkbox="" value="DE29973399" name="payer"/>
<div class="c-account-access-panel__checkbox-symbol"/>
2) Unselected
<label class="c-account-access-panel__checkbox " for="23336" data-js-checkbox-label="">
<input id="23336" class="c-account-access-panel__checkbox-input" type="checkbox"
data-label-for-value-missing="Please select at least one account from the options below" data-form-field-validation-on-grid=""
required="" checked="" data-js-checkbox="" value="DE29973399" name="payer"/>
<div class="c-account-access-panel__checkbox-symbol"/>
Thanks in advance!
回答1:
As per the Java Docs isSelected() method determines whether the element is selected or not. This operation only applies to <input>
elements such as checkboxes, options within a <select>
tag and radio buttons.
To validate if the desired checkbox is selected or not you can use the following code block:
boolean checkboxSelected = driver.findElement(By.xpath("//input[@class='c-account-access-panel__checkbox-input' and @name='payer']")).isSelected();
回答2:
If isSelected() is not working for you. Then , you can use JavascriptExecutor to do your task. Following JS statements shall let you know the state of target checkbox.
document.getElementById("23336").click();
document.getElementById("23336").checked;
The checked method returns true or false depending on the checkbox state.
回答3:
You can validate using getAttribute
method.
First select the webElement using any of the unique locator,
WebElement checkbox=driver.findElement(By.xpath(".//input[@type='checkbox']"));
If the checkbox is selected, then checkbox.getAttribute("checked")
will give the result as true
else, it will give the result as null
. So, you can add the condition using checkbox.getAttribute("checked")
回答4:
Use xpath expression like: (//div [@id='23336')[1] or (//div [@id='23336')[2] to make them into unique element then do .isselected ()
来源:https://stackoverflow.com/questions/50616459/how-to-validate-check-box-if-xpaths-are-same-in-case-of-selected-and-unselected