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

Question:

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?

Asked By: Anthon Santhez

||

Answers:

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
Answered By: Kawish Qayyum
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.