Etienne
Etienne

Reputation: 177

xpath to get checkbox inside label

I have this code

<label>
  <input type="radio" checked="checked" value="fOejPdlZIx83HA" name="btnRad">
  Test1
</label>
<label>
  <input type="radio" checked="checked" value="fdsaf4waff4sssd" name="btnRad">
  Test2
</label>
<label>
  <input type="radio" checked="checked" value="fg43fasd43wsat4" name="btnRad">
  Test3
</label>

I wish to access the radio button depending on the label text via xpath

I already tried multiple thing:

//input[@name='btnRad]']/following::*[contains(text(),'Test3')]
//label[text()='Test3']/input[@name='btnRad']
//*[contains(text(),'Test3')]

Even the last one return me nothing, so xpath think that "Test3" is not the text of the label... anyone have an idea how to do this?

Upvotes: 5

Views: 8188

Answers (2)

emcas88
emcas88

Reputation: 901

This works also //label[contains(.,'Test3')]/input .

Upvotes: 0

Robin
Robin

Reputation: 9644

Your expression is failing because your label has more that one text node: an empty string before the input, and Test3. The way you're using contains means it will only check the first text node, ie empty string.

Two ways of solving this:

  • eliminating the empty strings with normalize-space():

    //*[contains(text()[normalize-space()], 'Test3')]
    
  • querying each text():

    //*[text()[contains(.,'Test3')]]
    

For a more detailed explanation, see How to search for content in XPath in multiline text using Python?.

Upvotes: 7

Related Questions