QADeveloper
QADeveloper

Reputation: 21

Select by XPath element with EXACT text in label

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.

Upvotes: 2

Views: 5195

Answers (2)

Amado Saladino
Amado Saladino

Reputation: 2692

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.

Upvotes: 0

kjhughes
kjhughes

Reputation: 111726

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:

Upvotes: 1

Related Questions