How can I get and print `xpath:position` of an element?

Hello community!!! :slightly_smiling_face:

Well, as the title says, I want to get and print the xpath:position of an element. I use this way to find it and print it’s text:

	WebDriver driver = DriverFactory.getWebDriver()
	List<WebElement> h2_Tags = driver.findElements(By.xpath("//h2[contains(text(), 'Something')]"))
	
	if (h2_Tags.size() < 1) {
		println('Nothing found!!!')
	} else {
		for (h2_Tag in h2_Tags) {
			String txt = h2_Tag.getText()
			if (txt != null) {
				println(txt)
			}
		}
	}

But how can I get and print element’s xpath:position?

XPATH is not a two-way street (it’s a web standard but not required to build the web or, for that matter, your web page). It allows an interpretation of the DOM for those that need it.

JavaScript and CSS are used to build the web and are therefore both two-way streets. You can READ from and WRITE to a web page using JS/CSS to target elements in the DOM.

That said, I don’t think you need either of them, since your xpath will use the context you provide – see https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/position – in which case, you can count them in your loop:


int count = 0
for (h2_Tag in h2_Tags) { 
  count += 1
  String txt = h2_Tag.getText() 
  if (txt != null) { 
    println( txt + ": " + count.toString()) 
  }
}

Note count is incrementing outside your test for null H2 elements, which I assume is what you want.

1 Like

Thank you very much for your answer but I think it’s better to study it tomorrow… My brain right now is in boiling process!!! :dizzy_face: