Get Absolute XPath of Web Element

寵の児 提交于 2021-02-10 04:14:43

问题


I'm using Javascript in the following code to retrieve the absolute XPath of a web element:

public String getAbsoluteXPath(WebDriver driver)
{
    return  (String) driver.executeScript(
            "function absoluteXPath(element) {"+
                    "var comp, comps = [];"+
                    "var parent = null;"+
                    "var xpath = '';"+
                    "var getPos = function(element) {"+
                    "var position = 1, curNode;"+
                    "if (element.nodeType == Node.ATTRIBUTE_NODE) {"+
                    "return null;"+
                    "}"+
                    "for (curNode = element.previousSibling; curNode; curNode = curNode.previousSibling){"+
                    "if (curNode.nodeName == element.nodeName) {"+
                    "++position;"+
                    "}"+
                    "}"+
                    "return position;"+
                    "};"+

"if (element instanceof Document) {"+
"return '/';"+
"}"+

"for (; element && !(element instanceof Document); element = element.nodeType == Node.ATTRIBUTE_NODE ? element.ownerElement : element.parentNode) {"+
"comp = comps[comps.length] = {};"+
"switch (element.nodeType) {"+
"case Node.TEXT_NODE:"+
"comp.name = 'text()';"+
"break;"+
"case Node.ATTRIBUTE_NODE:"+
"comp.name = '@' + element.nodeName;"+
"break;"+
"case Node.PROCESSING_INSTRUCTION_NODE:"+
"comp.name = 'processing-instruction()';"+
"break;"+
"case Node.COMMENT_NODE:"+
"comp.name = 'comment()';"+
"break;"+
"case Node.ELEMENT_NODE:"+
"comp.name = element.nodeName;"+
"break;"+
"}"+
"comp.position = getPos(element);"+
"}"+

"for (var i = comps.length - 1; i >= 0; i--) {"+
"comp = comps[i];"+
"xpath += '/' + comp.name.toLowerCase();"+
"if (comp.position !== null) {"+
"xpath += '[' + comp.position + ']';"+
"}"+
"}"+

"return xpath;"+

"} return absoluteXPath(arguments[0]);", this.element);

}

Generally, this produces the correct result. However, if I navigate to stackoverflow.com and attempt to retrieve the XPath of the element with the XPath ID of: .//*[@id='hot-network-questions']/h4/a ("Hot Network Questions") the actual/expected XPath (according to Firebug) is: html/body/div[3]/div/div[3]/div[3]/h4/a however this script incorrectly produces the value of: /html[1]/body[1]/div[3]/div[1]/div[3]/div[4]/h4[1]/a[1]

Note the difference between div[3] and div[4] toward the end.


回答1:


On current page your code returns following value to me when try to identify WebElement

/html[1]/body[1]/div[3]/div[1]/div[1]/div[4]/div[6]/h4[1]/a[1]

Probably that is dependent on your session to the site and what sections are being displayed at that time; you can try seearching via xpath on the same session where you execute this code.



来源:https://stackoverflow.com/questions/43003935/get-absolute-xpath-of-web-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!