XPath使用ancestor轴返回label而非目标react-select-component节点问题
问题解答
核心问题
你的XPath写法逻辑确实写反了,XPath的返回结果由表达式最后一段路径指向的节点类型决定,你原表达式最后落点在label节点上,自然返回的是label而非目标下拉组件节点。
正确写法
你可以任选以下两种方案实现需求:
方案1:通过兄弟节点关系定位(更高效)
利用label和目标组件是同级兄弟节点的结构特性,直接定位:
- 选中「Data Source」对应的react-select节点:
//div[@class='editor-item']//label[text()='Data Source']/following-sibling::div[contains(@class, 'react-select-component')]
- 选中「Attribute」对应的react-select节点:
//div[@class='editor-item']//label[text()='Attribute']/following-sibling::div[contains(@class, 'react-select-component')]
方案2:按你原本的祖先筛选思路修改
如果要沿用你最初想用的ancestor轴逻辑,只需要把label匹配的条件作为目标节点的筛选谓语即可,最终落点保持在目标节点上:
- 选中「Data Source」对应的react-select节点:
//div[contains(@class, 'react-select-component')][ancestor::div[@class='editor-item']/label[text()='Data Source']]
- 选中「Attribute」对应的react-select节点:
//div[contains(@class, 'react-select-component')][ancestor::div[@class='editor-item']/label[text()='Attribute']]
说明
两种方案都兼容动态类名的场景,不需要依赖react生成的随机hash类名,仅通过固定的结构和label文本匹配。
内容的提问来源于stack exchange,提问作者Jeuke
相关产品推荐
相关产品推荐

