如何获得WebElement的父级 [英] How to get parent of WebElement

查看:1316
本文介绍了如何获得WebElement的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了

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

但我得到:


org.openqa.selenium.InvalidSelectorException:给定的选择器..
无效或者不会产生WebElement。出现以下错误

InvalidSelectorError:xpath表达式的结果
" .."是:[对象XrayWrapper [对象HTMLDocument]]。它
应该是一个元素。
命令持续时间或超时:10
毫秒
有关此错误的文档,

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,

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

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

推荐答案

有几种方法可以实现这一目标。如果您坚持使用XPath来执行此操作,则需要将上下文节点添加到定位器,如下所示:

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:

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

或者,您可以使用 JavascriptExecutor 界面,可能稍微高效一点。这看起来像这样:

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

// 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);

这篇关于如何获得WebElement的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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