【问题标题】:XPath partial of attribute known已知属性的 XPath 部分
【发布时间】:2010-10-26 01:12:29
【问题描述】:

我知道文档中属性的部分值,但不是全部。有没有我可以用来表示任何值的字符?例如,输入的标签值是“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>

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

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

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

【问题讨论】:

    标签: xpath string-matching


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 不,它应该看起来像//td[contains(concat(' ', label, ' '), ' Choice 1 ')]/input,否则它将匹配Choice 11
    • 就像给其他绊倒这个的人的注释:你必须使用@label,因为你指的是一个属性
    【解决方案2】:

    在尝试找到一种方法来测试节点是否具有不为空的属性“align”或包含文本值“text-align”的属性“style”时找到了 Ronald 的解决方案。这些是有问题的“节点”:

    <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!='']
    

    【讨论】:

      猜你喜欢
      • 2018-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多