I am using page object model. Here is XPath that I have written for Heading of the page and stored it in the heading WebElement variable:

@FindBy( xpath = "//div[@class='page-title category-title']")
private WebElement heading;`

My goal is to get or extract the XPath back from the element heading. I have tried printing it but the result I am getting is, System.out.println(heading)

gave me:

[[FirefoxDriver: firefox on WINDOWS (4520a9a1-c58b-4b34-ae3e-48613e6e7005)] -> xpath: //div[@class='page-title category-title']]`

And my expectation is :

//div[@class='page-title category-title'] 

as a string.


Just extract the class attribute of the element and create the xpath

String headingClass = heading.getAttribute("class");

String headingPath = "//div[@class='"+ headingClass + "']"

then use headingPath wherever you want.


I don't know why you want the output like this , but i can think of one way of getting you the class name instead of the whole xpath,


which will give you result as page-title category-title

Then you can prefix & postfix with you xpath string if only you want the output like that, then again as i said, i don't know why you need output string like that,


Want to know out of curiosity, whats the purpose of doing this?

  • 1
    Why? In my experience, because ExpectedConditions only work with locators and not with existing webelements... It's kind of silly to redefine an XPath if you already know the element.
    – FDM
    Nov 9 '15 at 19:31

We will be splitting the string with the delimitor "xpath:"

String[] a = heading.toString().split("xpath:");

//The length will be 2

// will print //div[@class='page-title category-title']
String source = "[[FirefoxDriver: firefox on WINDOWS (4520a9a1-c58b-4b34-ae3e-48613e6e7005)] -> xpath: //div[@class='page-title category-title']]";

//Split your Source from "->"
String[] temp = source.split("-> ");

//Split your Source from ": "
String[] temp2 = temp[1].split(": ");

//Access first index to get locator name
String locator = temp2[0];

//Access Second index to get locator value
String value = temp2[1].substring(0,temp2[1].length()-1);
  • This really doesn't add anything to the existing answers to a several-year-old question, and is actually less efficient with the multiple split operations, for no apparent added value.
    – c32hedge
    Sep 9 '19 at 16:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.