Java 如何获取 WebElement 的父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24267413/
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-08-14 11:12:08  来源:igfitidea点击:

How to get parent of WebElement

javaselenium

提问by Jae

I've tried

我试过了

private WebElement getParent(final WebElement webElement) {
    return webElement.findElement(By.xpath(".."));
}

But I'm getting:

但我得到:

org.openqa.selenium.InvalidSelectorException: The given selector .. is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: The result of the xpath expression ".." is: [object XrayWrapper [object HTMLDocument]]. It should be an element. Command duration or timeout: 10 milliseconds For documentation on this error,

org.openqa.selenium.InvalidSelectorException:给定的选择器 .. 无效或不会导致 WebElement。发生以下错误:InvalidSelectorError:xpath 表达式“..”的结果是:[object XrayWrapper [object HTMLDocument]]。它应该是一个元素。命令持续时间或超时:10 毫秒有关此错误的文档,

Is there a way to get the parent of current element? Thanks

有没有办法获取当前元素的父元素?谢谢

回答by twisted_coder

Alternatively, can you try using Javascript Executor?

或者,您可以尝试使用 Javascript Executor 吗?

WebElement childElement = driver.findElement(By.id("someIdHere"));

WebElement parent = (childElement) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].parentNode;", childElement);

回答by JimEvans

There are a couple of ways you can accomplish this. If you insist on using XPath to do it, you need to add the context node to the locator, like this:

有几种方法可以实现这一点。如果坚持使用 XPath 来做,则需要将上下文节点添加到定位器中,如下所示:

WebElement parentElement = childElement.findElement(By.xpath("./.."));

Alternatively, you can use the JavascriptExecutorinterface, which might be slightly more performant. That would look like this:

或者,您可以使用该JavascriptExecutor界面,它的性能可能稍高一些。那看起来像这样:

// NOTE: broken into separate statements for clarity. Could be done as one statement.
JavascriptExecutor executor = (JavascriptExecutor)driver;
WebElement parentElement = (WebElement)executor.executeScript("return arguments[0].parentNode;", childElement);