22

我知道文档中属性的部分值,但不是全部。有没有我可以用来表示任何值的字符?例如,输入的标签值是“A. Choice 1”。我知道它说的是“Choice 1”,但不知道它会在“Choice 1”之前说“A.”还是“B.”。以下是相关的 HTML。输入和标签还有其他属性,但是每次渲染页面的时候都不一样,所以我不能用它们作为引用:

<tr>
<td><input type="checkbox" /><label>A. Choice 1</label></td>
</tr><tr>
    <td><input type="checkbox" /><label>B. Choice 2</label></td>
</tr><tr>
<td><input type="checkbox" /><label>C. Choice 3</label></td>
</tr><tr>
     <td><input type="checkbox" /><label>D. Choice 4</label></td>
</tr>

这是我用来选择值为“Choice 1”的标签旁边的输入的XPath表达式,但 HTML 中 A 位于其前面:

//td[label="Choice 1"]/input

我不知道 HTML 中的 A 是 A、B 还是 C 等。但我知道正确的输入总是旁边有选择 1 文本。如果标签包含选项1,而不是等于选项 1,我怎么说选择它?

4

2 回答 2

46

您的 XPath 表达式应如下所示:

//td[contains(@label, 'Choice 1')]/input

您选择td具有包含标签的所有元素,Choice 1然后选择input这些元素中的td元素。

编辑:Tomalak 的评论正确地提出了一项改进,以防止与“Choice 11”(或“Choice 12345”,...)匹配。

于 2009-05-14T06:27:58.327 回答
5

在尝试找到一种方法来测试节点是否具有不为空的属性“对齐”或包含文本值“文本对齐”的属性“样式”时,找到了罗纳德的解决方案。这些是有问题的“节点”:

<node> 
  <p>This is left-aligned.</p> 
  <div align="left" >This is aligned LEFT using HTML attribute.</div> 
  <p style="text-align: center;" >This is centered using CSS style attribute.</p> 
  <div align="center" >This is CENTERED.</div> 
  <p style="text-align: right;" >This is right-aligned.</p> 
</this>

这个 xpath 表达式有效——感谢 Ronald 的回答为我指明了正确的方向:

//*[contains(@style, 'align') or @align!='']
于 2011-08-17T19:11:50.070 回答