XPath查找子元素的父元素 [英] XPath find parent of a child element
问题描述
我有这样的结构:
<div class="Container">
<div class="HighlightContainer">
<div class="NodeTextHighlightContainer">
<span class="TreeItemSelected">Products</span>
</div>
<button class="ContainerSelectedMenu" type="button"></button>
</div>
</div>
由于DOM的行为方式并试图保持动态,因此我只能定位包含文本产品"的范围.使用类似的东西:
Because of how the DOM behaves and trying to stay dynamic, I can only target the span that contains text Products. using something like:
Driver.FindElement(By.XPath("//div[contains(@class, 'Container')]/descendant::span[text() = 'Products']"));
但是,我需要基于该span元素将按钮定位到 class ="ContainerSelectedMenu"
的位置,最好的方法是什么?类似于获取Container子级的父div,然后找到button元素.
However, I need to target the button where class="ContainerSelectedMenu"
based of that span element, what is the best approach? Something like getting the parent div of the child of Container then finding the button element.
推荐答案
我已经找到了通过上下移动来实现此目的的不同方法,但是我现在更喜欢这种方法:
I've found different ways to do this by traversing back up and down which works fine, but my preference now is this approach:
xpath = "//div[contains(@class, 'Container') and descendant::span[text() = 'Products']]//button";
基本上,您将带有 text()='Products'
的后代放入您真正想要的 div
标记(即父标记)的要求的一部分.然后,您可以使用//button
或//button [@ class ='ContainerSelectedMenu']
Basically, you put the descendant with text() = 'Products'
as part of the requirement for the div
tag you really want, which is the parent. Then you can just search for the button easily with a //button
, or //button[@class='ContainerSelectedMenu']
实际上,您在这里不需要 descendant
轴,因此可以通过以下方式对其进行简化:
You actually don't need the descendant
axes here, so it can be simplified a bit with this:
xpath = "//div[contains(@class, 'Container') and .//span[text() = 'Products']]//button";
用英语...
- 找到一个 的
- 1.有一个
@class
,其中包含容器"和 - 2..具有后代
span
元素,其文字为产品" - 找到该
div
的后代,该后代是button
div
- Find a
div
that - 1. has a
@class
that contains "Container" and - 2. has a descendant
span
element with the text `Products - Find a descendant of that
div
that is abutton
这篇关于XPath查找子元素的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!