Jake
Jake

Reputation: 1097

How to click on checkboxes based on label text

I'm trying to use xPath to click on the yes checkbox but I can't seem to figure it out. I have tried

driver.find_element_by_xpath(".//label[following-sibling::input[contains(., 'Yes')]]").click() .

but this didn't work. In the past I have used

driver.find_element_by_xpath("//input[@id=(//label[text()=\"Phone Number\"]/@for)]")

to find text fields but I haven't been able to do the same for the checkbox. Any help would be much appreciated.

<dl data-validation="{&quot;checkboxes&quot;:
{&quot;required&quot;:true,&quot;and&quot;:
[{&quot;name&quot;:&quot;checkboxes&quot;,&quot;operator&quot;:&quot;checkboxes&quot;,&quot;options&quot;:{&quot;message&quot;:&quot;must select a value&quot;}}]}}" class="form">
  <dt><div class="form_response_label required" id="responses_2865807_label">Are you an Undergraduate Student?</div></dt>
<input id="responses_2865807_" name="responses[2865807][]" type="hidden">
  <div class="form-checkbox">
    <label for="responses_2865807_4737821">
      <input id="responses_2865807_4737821" name="responses[2865807][]" type="checkbox" value="4737821">
      Yes
</label>      </div>
  <div class="form-checkbox">
    <label for="responses_2865807_4737822">
      <input id="responses_2865807_4737822" name="responses[2865807][]" type="checkbox" value="4737822">
      No
</label>      </div>
<small><span class="right char_count"></span></small><div class="form-constraints"><div class="validation-summary" style="display: none;"><strong>Validation</strong><div class="explanation">Valid input may include: must select a value</div></div></div></dl>

My main focus is checking yes in the following code:

<label for="responses_2865807_4737821">
      <input id="responses_2865807_4737821" name="responses[2865807][]" type="checkbox" value="4737821">
"
      Yes
"
</label>

Now that I figured out how to find the check that says "Yes", how would I be able to select "Yes" specifying the label that came before it, in case I get into a situation where i need to change between Yes and No depending on the question? So in the example code above I would clarify that I am looking for the "Yes" checkbox labeled by "Are you an Undergraduate Student?"

Upvotes: 0

Views: 2245

Answers (1)

Jake
Jake

Reputation: 1097

Found the answer! Just needed to add .. instead of .

driver.find_element_by_xpath("//label/input[contains(..,'Yes')]").click()

Upvotes: 1

Related Questions