在 Selenium 中选择已知元素的父元素 [英] Select parent element of known element in Selenium

查看:32
本文介绍了在 Selenium 中选择已知元素的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 Selenium 1 选择某个元素.

I have a certain element that I can select with Selenium 1.

不幸的是,我需要单击父元素才能获得所需的行为.我可以轻松找到的元素具有不可选择的属性,使其无法点击.如何使用 XPath 向上导航?

Unfortunately I need to click the parent element to get the desired behaviour. The element I can easily locate has attribute unselectable, making it dead for clicking. How do I navigate upwards with XPath?

推荐答案

有几个选项.示例代码使用 Java,但移植到其他语言应该很简单.

There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
                                   "return arguments[0].parentNode;", myElement);

XPath:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));

WebElement

获取驱动

注意:如您所见,对于 JavaScript 版本,您需要 driver.如果您无法直接访问它,则可以使用以下方法从 WebElement 中检索它:

Obtaining the driver from the WebElement

Note: As you can see, for the JavaScript version you'll need the driver. If you don't have direct access to it, you can retrieve it from the WebElement using:

WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();

这篇关于在 Selenium 中选择已知元素的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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