selenium selector - how to check checkboxes?

懵懂的女人 提交于 2019-12-11 21:06:35

问题


I don't seem to be able to use click for checkboxes.
No error in the console, it shows the click but the checkbox isn't checked.
I have tried using both click and check but neither seem to check the checkbox. Using the database id (102) as suggested by the IDE recorder is not an option as the ID's change with each run.

I am trying: css=fieldset.choices ol li label input for my locator.

I also tried: //fieldset[@class='choices']//ol//li//label//input and again the console says clicked but the checkbox doesn't actually get checked in the browser.

I also tried: //input[@type='checkbox'] for the selector as it is the first checlbox on the screen but no luck with that, but no explicit error.

The HTML is:

<fieldset class="choices">
  <legend class="label">
    <label>
      Grades
    </label>
  </legend>
  <input id="school_grades_none" type="hidden" value="" name="school[grade_ids][]">
  </input>
  <ol class="choices-group">
    <li class="choice">
      <label for="school_grade_ids_102">
        <input id="school_grade_ids_102" type="checkbox" value="102" style="border: none" name="school[grade_ids][]">
        </input>
        PK3
      </label>
    </li>
    <li class="choice">
    ...
    </li>
    <li class="choice"></li>
    ...
    </li>
    <li class="choice"></li>
    ...
    </li>
    ...

回答1:


How about when you use id=school_grade_ids_102 as your locator, instead of the xpath or css.

UPDATE

How about you use contains like so

//input[contains(@id, 'school_grade_ids_')] # add [1] or [2], etc. at the end



回答2:


setCheckboxValue(By.id("checkboxId"), true /* or false*/);

public void setCheckboxValue(By by, boolean checked) {
        WebElement e = getDriver().findElement(by);
        if(!e.isSelected() && checked) {
            e.click();
        }
    }


来源:https://stackoverflow.com/questions/16651610/selenium-selector-how-to-check-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!