0

How can I know if a WebElement has childs or not?

Specifically, I have the following element:

enter image description here

The capabilities element, sometimes has span elements inside it and sometimes doesn't

I need the ones that has span childs.

How can I get them?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
dushkin
  • 1,939
  • 3
  • 37
  • 82

5 Answers5

1

The easiest way is to use try/except:

from selenium.common.exceptions import NoSuchElementException
try:
    driver.find_element_by_xpath('//td[@class="capabilities"]/span')
except NoSuchElementException:
    print("There are no child 'span' elements")
Andersson
  • 51,635
  • 17
  • 77
  • 129
  • Agreed. Use try, for if there are no spans, a NoSuchElementException is likely to be thrown by findElements(). – Machtyn Feb 17 '16 at 19:31
0

I must say that I had a bug in my code which caused me think I don't know the answer, but for everyone who might be interested, I used this:

List spans = capab.findElements(By.tagName("span"));

and then just checked

spans.size().
Nimantha
  • 6,405
  • 6
  • 28
  • 69
dushkin
  • 1,939
  • 3
  • 37
  • 82
0

You can try it (using has reference this case:

try{
     driver.findElement(By.xpath("//td[@class='capabilities']/span");
     System.out.println("There is span!");
     return true;
catch(NoSuchElementException e){
     System.out.println("No span!");
     return false;
    }
}
Community
  • 1
  • 1
0

To expound on @dushkin answer, we use findElements because its exception-safe :

By locator = By.xpath(".//td/span");
List<WebElement> subElements = capab.findElements(locator);

and then just checked

boolean hasSubElements = (subElements.size() > 0)
djangofan
  • 28,471
  • 61
  • 196
  • 289
0

You can check the inner child of web element through HTML dom manipulation, run the following command in your js file on documents load:

console.log(document.getElementsByClassName('capabilities'))

This will give you an array of html elements the class belongs to, iterate over each index and check if the innerHTML or children have span tag in it.

Dharman
  • 30,962
  • 25
  • 85
  • 135