Home > OS >  How to determine if an input element has "checked" attribute in Python Selenium?
How to determine if an input element has "checked" attribute in Python Selenium?

Time:09-06

There is a radio button whose buttons are controlled by <input/>. Its code is this:

<input id="IsEmployementProvided_0" name="IsEmployementProvided" type="radio" value="1" style="" xpath="1">

<input checked="checked" id="IsEmployementProvided_1" name="IsEmployementProvided" type="radio" value="0" xpath="1" style="">

As can be seen, the difference is the attribute "checked". So I am trying to find which one has a dot inside it, I mean which one has an attribute "checked". Here what I tried:

if(driver.find_element_by_xpath("//input[@id='IsEmployementProvided_1']").get_attribute("checked").contains("checked")):
   print("value = " driver.find_element_by_xpath("//input[@id='IsEmployementProvided_1']").get_attribute("checked").text)

Here error comes: Element has no attribute "contains". I am trying to determine if element has attribute "checked". Any help?

CodePudding user response:

If you try to get the value of checked you get true:

driver.find_element(By.XPATH, "//input[@id='IsEmployementProvided_1']").get_attribute("checked")

#Output
'true'

Whereas, it returns None for the other radio button, IsEmployementProvided_0.

So, you can do something like this:

if driver.find_element(By.XPATH, "//input[@id='IsEmployementProvided_1']").get_attribute("checked") == 'true':
    print('This is for checked!')
    # Do something

# OR simply skip the "== true" part.

if driver.find_element(By.XPATH, "//input[@id='IsEmployementProvided_1']").get_attribute("checked"):
    print('This is for checked!')
    # Do something

Also, find_elements_by_xpath is deprecated. Please use find_element instead. You'll have to import By for this:

from selenium.webdriver.common.by import By
  • Related