Home > Software design >  Why is XPath counting the wrong number of substrings?
Why is XPath counting the wrong number of substrings?

Time:11-13

I am trying to count the number of times a element with a partial text of "25516.B1-" appears on the page.

Right now I am trying this. However it returns 17 even though there are only 3 instances of the element on the page.

Count 3 basiskerntaken
${count}=  Get Element Count   //*[contains(.,"25516.B1-")]
Log To Console  ${count}

CodePudding user response:

I will use generic XPath and XML for the benefit of future readers, but the concepts are the same and can be applied to any framework that uses XPath, including . See addendum regarding selenium's limitations, however.

Counting the number of elements whose string value contains a substring,

count(//*[contains(.,"substring")])

will overcount the number of occurrences of the "substring" due to the nesting of elements. For example, both e and r have string values that contain "substring":

<r>
  <e>substring</e>
</r>

Instead, count the number of text nodes that contain the substring:

count(//text()[contains(.,"substring")])

There is only one such text node in the above example.

Note that this assumes that text is not partitioned across child elements:

<r>
  <e><b>subs</b>tring</e>
</r>

See also


Selenium-specific Addendum

@Trapli reports that "selenium insists to return webelements only, it won't return text nodes", here's a work-around that will return elements that selenium can then count:

//*[text()[contains(.,"substring")]]

This returns all elements that have a text node child that contains the provided "substring". It is unfortunate that selenium is limited in how it hosts XPath — most hosts are not so restrictive.

CodePudding user response:

If you know you have elements with that partial text, I would say using FindElements method to find all occurences of that method, it returns a list of elements , you can simply call List.count ();

List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));

elementname.count is your answer.

CodePudding user response:

Update the generic xpath to a bit more specific xpath as follows:

${count}=  Get Element Count   //tag_name[contains(.,"25516.B1-")]

More canonically:

${count}=  Get Element Count   //tag_name[contains(.,"25516") and contains(.,"B1-")]
  • Related