XPath查找子元素的父元素

编程入门 行业动态 更新时间:2024-10-25 08:20:15
本文介绍了XPath查找子元素的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这样的结构:

<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";

用英语...

  • 找到一个
  • 的 div
  • 1.有一个 @class ,其中包含容器"和
  • 2..具有后代 span 元素,其文字为产品"
  • 找到该 div 的后代,该后代是 button
  • 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 a button

更多推荐

XPath查找子元素的父元素

本文发布于:2023-10-08 02:35:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471264.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   XPath

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!