Find an element by text and get xpath - selenium webdriver junit

The XPath of an element is not a definitive value. An element can be found by many XPaths.

You cannot use Webdriver to extract an XPath and even if you could, it is unlikely to be the most efficient or sensible one, that can only be defined by the automator.


The question which you asked does not make any sense to me. I guess there might be a strong reason for you to 'want to do it' !

Your line of code

 String xpath = driver.findElement(By.name(test)).getAttribute("xpath");

will not return anything because there is no attribute 'xpath' in html elements. Please get your basics clear on to what xpath means??

if i have an html element as shown below

<input name = "username" value = "Name" readonly ="readonly">

i can get the values of attribute by using

driver.findElement(By.name("username").getAttribute("value");  // returns 'Name'

This will give me value of 'value' attribute

or

driver.findElement(By.name("username").getAttribute("readonly");  // returns 'readonly'

same as above !


You can also use this to crawl up and generate the xpath:

Call the method below with

generateXPATH(element, "");

The output will be something like:

/html[1]/body[1]/div[5]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/form[1]/div[2]/div[1]/input[2]

METHOD

private String generateXPATH(WebElement childElement, String current) {
    String childTag = childElement.getTagName();
    if(childTag.equals("html")) {
        return "/html[1]"+current;
    }
    WebElement parentElement = childElement.findElement(By.xpath("..")); 
    List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
    int count = 0;
    for(int i=0;i<childrenElements.size(); i++) {
        WebElement childrenElement = childrenElements.get(i);
        String childrenElementTag = childrenElement.getTagName();
        if(childTag.equals(childrenElementTag)) {
            count++;
        }
        if(childElement.equals(childrenElement)) {
            return generateXPATH(parentElement, "/" + childTag + "[" + count + "]"+current);
        }
    }
    return null;
}