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
  • 5,793
  • 5
  • 23
  • 56
dushkin
  • 1,769
  • 2
  • 27
  • 65

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
  • 49,746
  • 15
  • 64
  • 117
  • 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
  • 5,793
  • 5
  • 23
  • 56
dushkin
  • 1,769
  • 2
  • 27
  • 65
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
  • 26,842
  • 57
  • 182
  • 275
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
  • 26,923
  • 21
  • 73
  • 125