Search code examples
pythonseleniumselenium-webdrivercheckboxhtml-input

How to locate a checkbox to verify its state using Selenium and Python


I am trying to figure out if a checkbox on our website is in a checked state or not. The HTML for the checkbox is as follows:

<input id="ID_StaffIsRostered" name="ID_Rostering" type="checkbox" checked="" data-toggle="toggle" data-onstyle="success" data-size="sm" data-on="Yes" data-off="No" onchange="toggleRosteredStaff()">

I've tried finding this via these locators:

  1. (By.ID, "ID_StaffIsRostered")
  2. (By.XPATH, "input[@name='ID_Rostering']"
  3. (By.XPATH,"//*[@id='ID_StaffIsRostered']")
  4. (By.XPATH,"/html/body/div[1]/div/div[2]/div/div/div/div[2]/table[3]/tbody/tr/td/div[1]/div[2]/div/form/div/div[1]/div/label/div/input")
  5. (By.CSS_SELECTOR,"label:nth-child(1) > .btn-light .toggle-off")
  6. (By.XPATH,"//form[@id='ID_Form_Rostering']/div/div/div/label/div/div/label[2]")
  7. (By.XPATH,"//div/div/div/label/div/div/label[2]")

Nothing has worked so far. I can however select the div containing the checkbox, and the labels that the checkboxes switch between depending on what it is toggle to, the HTML is:

<div class="toggle btn btn-success btn-sm" data-toggle="toggle" style="width: 7.5px; height: 26px; min-width: 38px;">

and for the labels:

<div class="toggle-group"><label class="btn btn-success btn-sm toggle-on">Yes</label><label class="btn btn-light btn-sm toggle-off">No</label><span class="toggle-handle btn btn-light btn-sm"></span></div>

What are some alternative ways I can achiever this? Currently I'm using Selenium 4.0.0 with Python 3.9


Solution

  • As per the HTML Specification for Boolean attributes:

    A number of attributes are Boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

    If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

    The checked attribute can be represented in either of the ways:

    <input name=name id=id type=checkbox checked>
    <input name=name id=id type=checkbox checked="">
    <input name=name id=id type=checkbox checked="checked">
    

    Solution

    To verify the state of the checkbox you can probe the checked attribute and you can use the following code block:

    try:
      WebDriverWait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#ID_StaffIsRostered[name='ID_Rostering'][checked]")))
      print("Checkbox is in checked state")
    except:
      print("Checkbox is in unchecked state")