Search code examples
pythonselenium-webdriverattributesreturnnonetype

In python selenium get_attribute('value') does not return None when attribute does not exist in web element


I have a textbox in a form and I want to know if its blank. get_attribute() should return None if the attribute does not exist, but it's returning nothing, blank, empty space. I want to check that the attribute value does not exist in the web element below. Here's the web element:

<input type="text" name="newPhone2" size="12" maxlength="10">

and I want to return 'None' since 'value' attribute does not exist.

new_phone2 = self.driver.find_element(By.NAME, "newPhone2")
if new_phone2.get_attribute('value') == None:
 # Do blah blah blah

Even though value is not an attribute in the web element, get_attribute() does not return None. It returns nothing... For example:

print(new_phone2.get_attribute('value')) 

The element is found but prints blank space instead of None. I expected it to print None, so I can use None as my if condition. I even tried empty quotes as my condition, but that does not work.

Why is it blank and not returning None? If the value was there, it returns the value, but not returning None when value doesn't exist.

if web element have a value, it will return the value. For example,

<input type="text" name="newPhone2" value="123456' size="12" maxlength="10">
print(new_phone2.get_attribute('value')) 

This will print 123456. But if value attribute was not there, it does not return None.


Solution

  • If you check the return type of get_attribute it says str so if new_phone2.get_attribute('value') == None: will never be evaluated to true no matter what.

    When an element does not have an attribute that you are searching for it will return a "" which can be evaluated as a falsy value.

    Your updated code should be

    new_phone2 = self.driver.find_element(By.NAME, "newPhone2")
    if not new_phone2.get_attribute('value'):
     # Do blah blah blah
    

    Now if you want to consider white spaces to be a false too then you can use this instead

    if not new_phone2.get_attribute('value').strip():