Ruby Selenium Web Driver: How to Count Child Element Nodes of a Specific Node

Ruby Selenium Web Driver: How to count child element nodes of a specific node

There are some possible ways depending on how specific you want the XPath to be, f.e. if you simply want to count child elements of any name, then you can use * :

row.find_elements(:xpath => "*").length

and if you want to specifically count child elements of certain names i.e li and div :

row.find_elements(:xpath => "*[self::li|self::div]").length

Selenium how to determine if element has child?

As per your question to get all the Child Nodes of a Parent Node you can use FindElements() method with following-sibling::* attribute within xpath as follows :

  • Sample Code Block :

    List<IWebElement> textfields = new List<IWebElement>();
    textfields = driver.FindElements(By.XPath("//desired_parent_element//following-sibling::*"));

    Note : When FindElements() is used inconjunction with implicitly or explicitly waits, FindElements() method will return as soon as there are more than 0 items in the found collection, or will return an empty list if the timeout is reached.

  • XPath Details :

    • Description : This xpath technique is used to locate the sibling elements of a particular node.
    • Explanation : The xpath expression gets the all the sibling elements of the parent element located using desired_parent_element.

Selenium WebDriver by xpath: search by text in child elements

are you looking for something like below?

//\*[text()='Back']/ancestor::*[@class='mblToolBarButton mblToolBarButtonHasLeftArrow']

Count the number of elements are matching with for the given xpath expression

Try this code:

//Assume driver is intialized properly.
int iCount = 0;
iCount = driver.findElements(By.xpath("Xpath Value")).size());

The iCount has the number of elements having the same xpath value.

Get all child elements

Yes, you can achieve it by find_elements_by_css_selector("*") or find_elements_by_xpath(".//*").

However, this doesn't sound like a valid use case to find all children of an element. It is an expensive operation to get all direct/indirect children. Please further explain what you are trying to do. There should be a better way.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.stackoverflow.com")

header = driver.find_element_by_id("header")

# start from your target element, here for example, "header"
all_children_by_css = header.find_elements_by_css_selector("*")
all_children_by_xpath = header.find_elements_by_xpath(".//*")

print 'len(all_children_by_css): ' + str(len(all_children_by_css))
print 'len(all_children_by_xpath): ' + str(len(all_children_by_xpath))


Related Topics



Leave a reply



Submit