如何使用 xpath 查找具有两个特定后代的元素?
How do you use xpath to find an element with two specific descendants?
我有一个列表项的无序列表,其中包含动态生成的标签和值元素。我正在尝试验证该列表是否包含具有特定值的特定标签。
我正在尝试编写一个 xpath,它允许我使用量角器元素 (by.xpath) 找到包含已定义标签和值的父元素。给定一个列表,我需要能够通过特定属性的两个后代的组合找到任何单个 li。例如,一个 li 元素包含具有 class=label 和 text=Color 的任何后代以及具有 text=Blue.
的任何后代
<ul>
<li>
<span class='label'> Car </span>
<p> Ford </p>
</li>
<li>
<span class='label'> Color </span>
<p> <span>My favorite color is</span> : <webl>Blue</webl></p>
</li>
<li>
<span class='label'> Name </span>
<p> Meri </p>
</li>
<li>
<span class='label'> Pet </span>
<p> Cats <span>make the best pets</span> </p>
</li>
我尝试了以下模式的几种变体:
//li[.//*[@class="label" | contains(text(), 'Color')] | .//*[contains(text(), 'Blue')]
这是我认为最接近的一次,但由于不是有效的 xpath 而返回。几个小时以来,我一直在查看参考资料、备忘单和 SO 问题,但我并没有更深入地了解我做错了什么。最终我需要用变量替换文本,但现在我只需要解决这个问题。
a list item that contains, at any depth,
any tag with a class of 'label' and text of x
AND
any tag with text y
谁能告诉我我做错了什么?我是不是让它太复杂了?
您获得无效 xPath 的原因是:
The |, or union, operator returns the union of its two operands,
which must be node-sets..
但是,由于您在一个节点内使用过,所以您遇到了问题。为了满足您的要求,xpath 可以正常工作:
//*[@class="label" and contains(text(),'Color')]//ancestor::li//*[contains(text(), 'Blue')]
根据您共享的 HTML 找到包含 class='label'
和 text=Color
AND[=24 后代的 <li>
元素=] 任何具有 text=Blue
的后代都可以使用以下 xpath based :
//li[./span[@class='label' and contains(., 'Color')]][.//webl[contains(., 'Blue')]]
概念验证:
我有一个列表项的无序列表,其中包含动态生成的标签和值元素。我正在尝试验证该列表是否包含具有特定值的特定标签。
我正在尝试编写一个 xpath,它允许我使用量角器元素 (by.xpath) 找到包含已定义标签和值的父元素。给定一个列表,我需要能够通过特定属性的两个后代的组合找到任何单个 li。例如,一个 li 元素包含具有 class=label 和 text=Color 的任何后代以及具有 text=Blue.
的任何后代<ul>
<li>
<span class='label'> Car </span>
<p> Ford </p>
</li>
<li>
<span class='label'> Color </span>
<p> <span>My favorite color is</span> : <webl>Blue</webl></p>
</li>
<li>
<span class='label'> Name </span>
<p> Meri </p>
</li>
<li>
<span class='label'> Pet </span>
<p> Cats <span>make the best pets</span> </p>
</li>
我尝试了以下模式的几种变体:
//li[.//*[@class="label" | contains(text(), 'Color')] | .//*[contains(text(), 'Blue')]
这是我认为最接近的一次,但由于不是有效的 xpath 而返回。几个小时以来,我一直在查看参考资料、备忘单和 SO 问题,但我并没有更深入地了解我做错了什么。最终我需要用变量替换文本,但现在我只需要解决这个问题。
a list item that contains, at any depth,
any tag with a class of 'label' and text of x
AND
any tag with text y
谁能告诉我我做错了什么?我是不是让它太复杂了?
您获得无效 xPath 的原因是:
The |, or union, operator returns the union of its two operands, which must be node-sets..
但是,由于您在一个节点内使用过,所以您遇到了问题。为了满足您的要求,xpath 可以正常工作:
//*[@class="label" and contains(text(),'Color')]//ancestor::li//*[contains(text(), 'Blue')]
根据您共享的 HTML 找到包含 class='label'
和 text=Color
AND[=24 后代的 <li>
元素=] 任何具有 text=Blue
的后代都可以使用以下 xpath based
//li[./span[@class='label' and contains(., 'Color')]][.//webl[contains(., 'Blue')]]
概念验证: