How to test if a WebElement Attribute exists using Selenium Webdriver

Viewed 15495

I am testing for whether elements on the page such as //img or //i have an alt attribute.

I can't find a way to detect when the attribute does not exist at all.

Here's the WebElement. Just an img with no alt attribute.

<img class="gsc-branding-img" src="https://www.google.com/cse/static/images/1x/googlelogo_grey_46x15dp.png" srcset="https://www.google.com/cse/static/images/2x/googlelogo_grey_46x15dp.png 2x"/>

Here's my code trying to determine the alt's existence. I know it's not all necessary, I was just trying everything.

WebElement we == driver.findElement(By.xpath("(//img)[1]"));
String altAttribute = we.getAttribute("alt");

if(altAttribute == null || altAttribute =="" || altAttribute == " ")
     {
     //attribute not found
     }

It seems like it is returning an empty string... For example, the following code returns "beforeAfter"

System.out.println("before"+altAttribute+"After");

However, my if statement does not catch the return, so I don't know what to do.

5 Answers

Assume we is the web element <img class="gsc-branding-img" ....

  • we.getAttribute("blabla") returns null
  • we.getAttribute("class") returns "gsc-branding-img" So, we can check like this:
if(we.getAttribute("blabla") == null){
    System.out.println("Attribute does not exist");
}
else {
    System.out.println("Attribute exists!");
}

Similarly for python bindings of selenium:

we.get_attribute('blabla') returns None

Related