在Java中获取WebElement的Absolute XPath

时间:2017-03-23 01:26:22

标签: java html xpath

我知道如何使用以下代码通过Javascript获取元素的绝对XPath:

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);

}

但是,我不确定如何通过Java直接执行此操作,例如我可以访问HTML source

怎么可能呢?

Google.com上徽标的绝对XPath将是:

html/body/div[1]/div[6]/span/center/div[1]/img

而Google徽标的相对XPath为:.//*[@id='hplogo']

如果给定元素+ HTML,我如何获得web元素的绝对XPath?

由于

1 个答案:

答案 0 :(得分:0)

希望下面的逻辑有帮助

function absolutePath(element) {
    if (element.tagName.toLowerCase() == 'html')
        return '/html[1]';
    if (element === document.body)
        return '/html[1]/body[1]';
    var ix = 0;
    var siblings = element.parentNode.childNodes;
    for (var i = 0; i < siblings.length; i++) {
        var sibling = siblings[i];
        if (sibling === element)
            return absolutePath(element.parentNode) + '/' + element.tagName.toLowerCase() + '[' + (ix + 1) + ']';
        if (sibling.nodeType === 1 && sibling.tagName.toLowerCase() === element.tagName.toLowerCase())
            ix++;
    }
}

它是简化得多的版本