How to test if a WebElement Attribute exists using Selenium Webdriver
if the attribute is not present, it should return null, if it's present and not set then it will return empty string. I think that's the case in your example, if so. Then you should use equal
method to compare string rather than ==
operator.
Below example is about google search box, xxx attribute is not present for search box and so it will return null
driver = new ChromeDriver(); driver.get("http://google.com"); WebElement ele = driver.findElement(By.name("q")); String attr = ele.getAttribute("xxx"); if (attr == null){ System.out.print("Attribute does not exist"); } else if (attr.equals("")){ System.out.print("Attribute is empty string"); }
You can try it out yourself by writing the following html and saving it as test. html:
<html> <head> </head> <body> <p id="one">one</p> <p id="two" data-se="">two</p> <p id="three" data-se="something">three</p> </body></html>
Then write a web driver script that looks like this:
driver.get("file:///<PATH_TO_HTML_ABOVE>/test.html");WebElement one = driver.findElement(By.id("one"));WebElement two = driver.findElement(By.id("two"));WebElement three = driver.findElement(By.id("three"));System.out.println("Does one have the data-se attribute?: '" + one.getAttribute("data-se") + "'");System.out.println("Does two have the data-se attribute?: '" + two.getAttribute("data-se") + "'");System.out.println("Does three have the data-se attribute?: '" + three.getAttribute("data-se") + "'");
Which will give you the following output:
Does one have the data-se attribute?: 'null' Does two have the data-se attribute?: '' Does three have the data-se attribute?: 'something'
Instead of checking the attribute, you should list the elements with the missing attribute with a selector:
List<WebElement> elems = driver.findElements(By.cssSelector("img:not([alt])"));if (elems.size() > 0) { // found images with alt attribute missing}
I think you need to handle the null value first. if(null == we.getAttribute("alt")){ }