How can I know if a WebElement has childs or not?
Specifically, I have the following element:
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?
How can I know if a WebElement has childs or not?
Specifically, I have the following element:
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?
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")
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;
}
}
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)
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.