获取Web元素的绝对XPath [英] Get Absolute XPath of Web Element
问题描述
我在以下代码中使用Javascript来检索Web元素的绝对 XPath
:
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);
}
通常,这会产生正确的结果.但是,如果我导航到stackoverflow.com并尝试检索XPath ID为以下元素的元素的XPath: .//* [@ id ='hot-network-questions']/h4/a
(热点网络问题")实际/预期的XPath(根据 Firebug
)是: 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]
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]
请注意div [3]和div [4]之间的差异.
Note the difference between div[3] and div[4] toward the end.
推荐答案
在当前页,当您尝试确定代码时,代码会向我返回以下值 WebElement
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]
这可能取决于您到站点的会话以及当时正在显示的部分;您可以在执行此代码的同一会话上尝试通过xpath进行渗透.
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.
这篇关于获取Web元素的绝对XPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!