Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Both of the above answers suffer from the same problem. By returning the completed XPath with the <code>.toLowerCase()</code> function called, any XPath containing an id with a capital letter will not work. </p> <p>Example: <code>//div[@id="deviceblock-1111"]</code> will not work on tag <code>&lt;div id="deviceBlock-1111"&gt;</code> </p> <p>You could however just remove the <code>.toLowerCase()</code> call off the return but you'll end up with XPath's looking like this: <code>//DIV[@id="deviceBlock-1111"]/DIV[2]/SELECT[1]/OPTION[5]</code> </p> <p>To solve this use the function below.</p> <pre><code>public String GetElementXPath(WebElement element, WebDriver driver) { return (String) ((JavascriptExecutor) driver).executeScript( "getXPath=function(node)" + "{" + "if (node.id !== '')" + "{" + "return '//' + node.tagName.toLowerCase() + '[@id=\"' + node.id + '\"]'" + "}" + "if (node === document.body)" + "{" + "return node.tagName.toLowerCase()" + "}" + "var nodeCount = 0;" + "var childNodes = node.parentNode.childNodes;" + "for (var i=0; i&lt;childNodes.length; i++)" + "{" + "var currentNode = childNodes[i];" + "if (currentNode === node)" + "{" + "return getXPath(node.parentNode) + '/' + node.tagName.toLowerCase() + '[' + (nodeCount+1) + ']'" + "}" + "if (currentNode.nodeType === 1 &amp;&amp; " + "currentNode.tagName.toLowerCase() === node.tagName.toLowerCase())" + "{" + "nodeCount++" + "}" + "}" + "};" + "return getXPath(arguments[0]);", element); } </code></pre> <p>This will return a correctly formatted, unique XPath from your WebElement. </p> <p><code>//div[@id="deviceBlock-1111"]/div[2]/select[1]/option[5]</code></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload