Search code examples
pythonselenium-webdrivercheckboxwebdriver

How to resolve is_selected() not returning True even if the checkbox is selected?


I'm using Selenium + python to check the status of a checkbox but it always returns False.

Checkbox HTML Checkbox HTML

I'm using XPath

value = "//span[@title='Select Physical']"

I'm using the code below to evaluate if the checkbox is checked or not.

if driver.find_element(By.XPATH, value).is_selected():
    self.click_button_by_xpath(value)

Not sure what I'm I missing here.


Solution

  • is_selected() only works on a checkbox or radio button according to the docs.

    Without being able to see the other relevant HTML, I'm assuming that the aria-checked="true" attribute indicates whether the checkbox is checked. Assuming that's true, the code below should work.

    button = driver.find_element(By.XPATH, value)
    if button.get_attribute("aria-checked") == "true":
        button.click()