javascript 如何通过单击 html 元素获取 xpath

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18606760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:33:26  来源:igfitidea点击:

How to get the xpath by clicking an html element

javascriptjqueryhtmlxpath

提问by Piyush

I am quite new to programming and have to generate a Xpath on clicking an html element. for example :if i have clicked on text box of username then it should give me the xpath like html/head/body/tr[1]/table[2]..... etc etc. The main thing is i can not use firebug as my application is thoroughly goin to run on IE. I have seen lot of fxn to get xpath and tried to integrate it but i am not getting the return value. A simple code snippet where i used jquery click() function to retrieve the value is not working.The thing is i am unable to pass the html element in the function.The xpath function i have taken from this site only. My code is below.

我对编程很陌生,必须在单击 html 元素时生成 Xpath。例如:如果我点击了用户名的文本框,那么它应该给我像 html/head/body/tr[1]/table[2]..... 等的 xpath。主要是我不能使用 firebug,因为我的应用程序完全可以在 IE 上运行。我已经看到很多 fxn 来获取 xpath 并尝试集成它,但我没有得到返回值。我使用 jquery click() 函数检索值的一个简单代码片段不起作用。问题是我无法在函数中传递 html 元素。我仅从该站点获取了 xpath 函数。我的代码如下。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<style> 
p
{ 
   color: red;    
   margin: 5px;
   cursor: pointer; 
}  
p:hover
 { 
   background: yellow; 
 }
</style> 
<script src="http://code.jquery.com/jquery-1.9.1.js">
</script>
</head>
<body> 
<p id ="test">First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>

$( "#test" ).click(function() { var value= $(this).getXPath();
alert(value) });

function getXPath( element )
{
var val=element.value;
alert("val="+val);
    var xpath = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        alert(element);
        var id = $(element.parentNode).children(element.tagName).index(element) + 1;
        id > 1 ? (id = '[' + id + ']') : (id = '');
        xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }
    return xpath;
}
</script>
</body>
</html> 

回答by Michael B.

change script to

将脚本更改为

$( "#test" ).click(function() { var value= getXPath( this  );
alert(value) });

function getXPath( element )
{
var val=element.value;
    //alert("val="+val);
    var xpath = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        //alert(element);
        var id = $(element.parentNode).children(element.tagName).index(element) + 1;
        id > 1 ? (id = '[' + id + ']') : (id = '');
        xpath = '/' + element.tagName.toLowerCase() + id + xpath;
    }
    return xpath;
}

回答by Sankumarsingh

In IE You need to insatll Bookmarklets.

在 IE 中,您需要安装 Bookmarklets。

STEPS TO INSTAL BOOKMARKLETS

安装书签的步骤

1)Open IE

1)打开浏览器

2)Type about:blank in the address bar and hit enter

2) 在地址栏中输入 about:blank 并回车

3)From Favorites main menu select--->Add favorites

3)从收藏夹主菜单选择--->添加收藏夹

4) In the Add a favorite popup window enter name GetXPATH1.

4) 在添加收藏夹弹出窗口中输入名称 GetXPATH1。

5)Click add button in the add a favorite popup window.

5)在添加收藏夹弹出窗口中单击添加按钮。

6)Open the Favorites menu and right click the newly added favorite and select properties option.

6) 打开收藏夹菜单,右键单击新添加的收藏夹并选择属性选项。

7)GetXPATH1 Properties will open up. Select the web Document Tab.

7)GetXPATH1 属性将打开。选择 Web 文档选项卡。

8)Enter the following in the URL field.

8) 在 URL 字段中输入以下内容。

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"']";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if(rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1]';break;}ns=ns.nextSibling;}}return nodeExpr;}

javascript:function getNode(node){var nodeExpr=node.tagName;if(!nodeExpr)return null;if(node.id!=''){nodeExpr+="[@id='"+node.id+"'] ";return "/"+nodeExpr;}var rank=1;var ps=node.previousSibling;while(ps){if(ps.tagName==node.tagName){rank++;}ps=ps.previousSibling;}if (rank>1){nodeExpr+='['+rank+']';}else{var ns=node.nextSibling;while(ns){if(ns.tagName==node.tagName){nodeExpr+='[1] ';break;}ns=ns.nextSibling;}}return nodeExpr;}

9)Click Ok. Click YES on the popup alert.

9) 单击确定。单击弹出警报上的“是”。

10)Add another favorite by following steps 3 to 5, Name this favorite GetXPATH2 (step4)

10) 按照步骤 3 到 5 添加另一个收藏夹,将此收藏夹命名为 GetXPATH2(步骤 4)

11)Repeat steps 6 and 7 for GetXPATH2 that you just created.

11) 对刚刚创建的 GetXPATH2 重复步骤 6 和 7。

12)Enter the following in the URL field for GetXPATH2

12) 在 GetXPATH2 的 URL 字段中输入以下内容

javascript:function o_o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push(pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/');clipboardData.setData("Text", xpath);}o_o();

javascript:function o_ o(){var currentNode=document.selection.createRange().parentElement();var path=[];while(currentNode){var pe=getNode(currentNode);if(pe){path.push (pe);if(pe.indexOf('@id')!=-1)break;}currentNode=currentNode.parentNode;}var xpath="/"+path.reverse().join('/'); clipboardData.setData("Text", xpath);}o_o();

13)Repeat Step 9.

13) 重复步骤 9。

You are all done!!

你们都完成了!!

Now to get the XPATH of elements just select the element with your mouse. This would involve clicking the left mouse button just before the element (link, button, image, checkbox, text etc) begins and dragging it till the element ends. Once you do this first select the favorite GetXPATH1 from the favorites menu and then select the second favorite GetXPATH2. At his point you will get a confirmation, hit allow access button. Now open up a notepad file, right click and select paste option. This will give you the XPATH of the element you seek.

现在要获取元素的 XPATH,只需用鼠标选择元素。这将涉及在元素(链接、按钮、图像、复选框、文本等)开始之前单击鼠标左键并拖动它直到元素结束。完成此操作后,首先从收藏夹菜单中选择收藏夹 GetXPATH1,然后选择第二个收藏夹 GetXPATH2。此时您会得到确认,点击允许访问按钮。现在打开一个记事本文件,右键单击并选择粘贴选项。这将为您提供所需元素的 XPATH。

回答by Indra Yadav

This could help you

这可以帮助你

fiddle

小提琴

$('p').click(function(){
parentEls = $(this).parents()
            .map(function () {
                  return this.tagName;
                })
            .get().join(", ");

    alert(parentEls);

    });

回答by TC Tar?m K?y ??leri

This code give path of element.

这段代码给出了元素的路径。

      $('a').click(function () {
            var XPATH = "";
            var FindParent = true;
            var _parent = $(this);

            while (FindParent) {
                var myParent = _parent.parent();
                if (myParent != null) {
                    XPATH += myParent.prop("tagName") + "/";
                    _parent = myParent;
                }
                else {
                    FindParent = false;
                }

            }
        })