获取Web元素的绝对XPath

时间:2017-03-24 15:51:54

标签: java html selenium xpath

我在以下代码中使用Javascript来检索网络元素的绝对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); }

.//*[@id='hot-network-questions']/h4/a

通常,这会产生正确的结果。但是,如果我导航到stackoverflow.com并尝试检索XPath ID为:Firebug(" Hot Network Questions")的元素的XPath,则实际/预期的XPath(根据{ {1}}):html/body/div[3]/div/div[3]/div[3]/h4/a但是此脚本错误地生成了值:/html[1]/body[1]/div[3]/div[1]/div[3]/div[4]/h4[1]/a[1]

注意div [3]和div [4]之间的差异。

1 个答案:

答案 0 :(得分:0)

current页面上,当您尝试识别时,您的代码会向我返回以下值 WebElement

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

可能这取决于您与网站的会话以及当时正在显示的部分;您可以在执行此代码的同一会话中尝试通过xpath进行查看。