gpt4 book ai didi

java - 获取 Web 元素的绝对 XPath

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:22 24 4
gpt4 key购买 nike

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

}

通常,这会产生正确的结果。但是,如果我导航到 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]

注意最后 div[3] 和 div[4] 之间的区别。

最佳答案

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

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

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

关于java - 获取 Web 元素的绝对 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com