webdriver:获取元素的xpath? [英] webdriver: get element's xpath?

查看:37
本文介绍了webdriver:获取元素的xpath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以返回 WebElement 的 xpath ?

is it possible to return a WebElement's xpath ?

推荐答案

不是直接来自 WebDriver,但如果你真的需要,你可以伪造它:

Not directly from WebDriver, but you can fake it if you really need to:

public String getElementXPath(WebDriver driver, WebElement element) {
    return (String)((JavascriptExecutor)driver).executeScript("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element);
}

Javascript 来自 这篇文章,缩小到适合一行.它可能并不完美,但可以让您知道去哪里.大多数驱动程序实现了 JavascriptExecutor 界面,并具有在浏览器中执行 Javascript 的能力.executeScript 可以返回任何原始 JavaScript 类型、一个 HTML 元素或上述任何一个的非嵌套列表.

The Javascript is from this post, minified to fit on one line. It may not be perfect, but could give you an idea of where to go. Most drivers implement the JavascriptExecutor interface and have the capability of executing Javascript in the browser. executeScript can return any primitive JavaScript type, an HTML element, or non-nested list of any of the preceding.

并非所有浏览器都以相同的方式支持 xpath,因此请小心使用这些 xpaths 来选择元素.此外,并非所有浏览器都具有本机 xpath 支持(cough IE cough),因此在这种情况下是伪造的.

Not all browsers support xpath the same way, so be careful if using these xpaths to select elements. Also, not all browsers have native xpath support (cough IE cough), so it was faked in that case.

这篇关于webdriver:获取元素的xpath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆