2

I am trying to find the XPath that would select a checkbox with an EXACT label. However, I cannot use contains() because there may be several options for the label I am trying to locate.

Here is the html:

  <li> 
    <label class="checkbox"> 
      <input id="role_id_9" name="user[role_ids][]" type="checkbox" value="9"/> Pharmacist with Prescriptive Authority
    </label> 
  </li>  
  <li> 
    <label class="checkbox"> 
      <input id="role_id_10" name="user[role_ids][]" type="checkbox" value="10"/> Pharmacist
    </label> 
  </li>  
  <li> 
    <label class="checkbox"> 
      <input id="role_id_83" name="user[role_ids][]" type="checkbox" value="83"/> Out of State Pharmacist
    </label> 
  </li> 

I am trying to find the checkbox with the label 'Pharmacist'. This xpath would normally work

 //label[contains(., 'Pharmacist')]/input[1]

except that 'Pharmacist with Prescriptive Authority' is listed BEFORE Pharmacist, so because it contains the word 'Pharmacist' it is selected instead. I can not use IDs because my tests are used in multiple environments and the IDs change. It is also important to note that the order in which these display may vary by environment as well.

My situation was just a little different from the linked example as my input element was inside the label element.

kjhughes
  • 106,133
  • 27
  • 181
  • 240
QADeveloper
  • 21
  • 1
  • 4
  • Possible duplicate of [How to use XPath contains() for specific text?](https://stackoverflow.com/questions/39650007/how-to-use-xpath-contains-for-specific-text) – kjhughes Oct 22 '17 at 22:49

2 Answers2

1

This XPath,

//label[normalize-space()='Pharmacist']/input

will select those input elements that are contained in a label element whose string-normalized string value is Pharmacist.

See also:

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • Thank you SO much! This worked. I tried to +1 you but my rep is too low. Hopefully someone else will com along and +1 this. Thank you!! – QADeveloper Oct 22 '17 at 23:35
  • You're welcome. Please [**accept**](http://meta.stackoverflow.com/q/5234/234215) this answer if it's helped. (That takes no rep.) Thanks. – kjhughes Oct 23 '17 at 00:14
0

I copied your HTML code into a test html page and tried getting the checkbox by label.

"//label[text()[contains(.,'Out')]]//input[@type='checkbox']"

This one for the third checkbox. Notice provide a unique subtext into your XPATH expression as XPATH will return the first element matching your expression. i.e. dun provide 'Pharmacist', of course, all checkbox elements have this subtext.

Amado Saladino
  • 2,114
  • 23
  • 25