问题
I want to validate the state of toggle button, whether it is ON or OFF? I tried a lot but the one thing which is very strange is that, HTML is not getting changed in both the state.
<div class="c-form-section">
<div class="o-grid">
<div class="o-grid__col o-grid__col--1-of-1">
<div class="o-grid__col o-grid__col--1-of-1 o-grid__col-tb--1-of-2"> </div>
<div class="o-grid__col o-grid__col--1-of-1 o-grid__col-tb--1-of-2 o-grid__col--spaced-tb">
<div class="u-spaced-top--quarter-square">
<section class="c-permission-fields">
<div class="c-permission-fields__block c-permission-fields__block--main ">
<div class="u-display--flex">
<div class="u-flex--grow">
<div>
<label class="c-control c-control--toggle ">
<input id="cardActivity" class="c-control__input" type="checkbox" value="1" name="cardActivity">
<span class="c-control__fake-input"></span>
<span class="c-control__label"> </span>
</label>
</div>
</div>
</div>
How m i suppose to validate this? Thanks in advance!
回答1:
You can use is_selected()
(Python):
elem = driver.find_element_by_id("cardActivity")
if elem.is_selected():
# do stuff if selected
is_selected()
will check if checkbox is selected.
In Java would be like this:
WebElement element = driver.findElement(By.id("cardActivity"));
if (element.isSelected()){
//do stuff
}
回答2:
In Java binding:
boolean isChecked = driver.findElement(By.id("cardActivity")).isSelected();
or here is a method for checking/unchecking control:
public void checkCheckbox(boolean checked)
{
WebElement checkbox = driver.findElement(By.id("cardActivity"));
if (checked != checkbox.isSelected())
{
checkbox.click();
}
}
This code can be generalized for all controls of the same type but this is just general logic.
回答3:
Dears follows a snippet using get_attribute("checked") method. Analyzing the attributes, it fits perfectly for what you want to do.
switch = instance.find_by_id(SWITCH_ID)
if switch.get_attribute("checked") == "false":
# do something because the toggle button is unchecked
来源:https://stackoverflow.com/questions/51650695/how-can-check-the-state-on-or-off-of-toggle-button-in-selenium