Search code examples
webdriver

webdriver: get element's xpath?


Is it possible to return a WebElement's xpath?


Solution

  • Not directly from WebDriver, but you can fake it if you really need to:

    public String getElementXPath(WebDriver driver, WebElement element) {
        return (String)((JavascriptExecutor)driver).executeScript("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element);
    }
    

    The Javascript is from this post, minified to fit on one line. It may not be perfect, but could give you an idea of where to go. Most drivers implement the JavascriptExecutor interface and have the capability of executing Javascript in the browser. executeScript can return any primitive JavaScript type, an HTML element, or non-nested list of any of the preceding.

    Not all browsers support xpath the same way, so be careful if using these xpaths to select elements. Also, not all browsers have native xpath support (cough IE cough), so it was faked in that case.