XPath partial of attribute known

ⅰ亾dé卋堺 提交于 2019-12-18 11:53:39

问题


I know the partial value of an attribute in a document, but not the whole thing. Is there a character I can use to represent any value? For example, a value of a label for an input is "A. Choice 1". I know it says "Choice 1", but not whether it will say "A. " or "B. " before the "Choice 1". Below is the relevant HTML. There are other attributes for the input and the label, but they are not the same every time the page is rendered, so I can't use them as references:

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

This is the XPath expression I'm using to select the input next to the label with the value of "Choice 1", except that the A is in front of it in the HTML:

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

I don't know if the A in the HTML will be an A, B, or C, etc. But I do know that the correct input will always have the Choice 1 text next to it. How do I say to select it if the label contains Choice 1, as opposed to being equal to choice 1?


回答1:


Your XPath expression should look like this:

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

You select all td elements that have a label that contains Choice 1 and then you select the input elements inside these td elements.

EDIT: Tomalak's comment correctly suggests an improvement to prevent a match against 'Choice 11' (or 'Choice 12345', ...).




回答2:


Found Ronald's solution while trying to find a way to test whether a node has either an attribute 'align' that is not empty OR an attribute 'style' that contains text value 'text-align'. These are the 'nodes' in question:

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

This xpath expression worked -- thanks to Ronald's answer that pointed me in the right direction:

//*[contains(@style, 'align') or @align!='']


来源:https://stackoverflow.com/questions/861008/xpath-partial-of-attribute-known

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!