Jake
Jake

Reputation: 1097

Selecting xpath input given label

So I normally use driver.find_element_by_xpath('//input[@id=(//*[contains(text(), "User Name")]/@for)]') to enter information into text boxes, but this hasn't been working for the following code:

<div class="form-group text-entry required ">
  <div class="label-set" id="answerTextBox-30918642">Primary User Name (First and Last Name)</div>
  <div class="group-set" role="group" aria-labelledby="answerTextBox-30918642">
    <input id="pageResponse_Responses_Index" name="pageResponse.Responses.Index" type="hidden" value="fta30918642">
    <input class="freeTextAnswerId form-control" id="pageResponse_Responses_fta30918642__FreeTextAnswerId" name="pageResponse.Responses[fta30918642].FreeTextAnswerId" type="hidden" value="30918642">
    <label for="answerTextBox-30918642-free" class="sr-only">Write-In Answer</label>
    <input class="form-control free-text" id="answerTextBox-30918642-free" name="pageResponse.Responses[fta30918642].FreeText" type="text" value="">
  </div>
</div>

I tried messing with the xpath to select the input,

driver.find_element_by_xpath("//label[contains(.,'User Name')]/following-sibling::input[1]")

but so far nothing I've tried so far has worked correctly. This works to find the element containing the label, driver.find_element_by_xpath("//*[contains(text(), 'User Name')]"), but my issue is then selecting the input to send keys to.

Upvotes: 0

Views: 1934

Answers (2)

Jake
Jake

Reputation: 1097

So I was able to get it working integration Santhosh's suggestion:

//*[contains(text(), \"User Name\")]/../div//input[@class='form-control free-text']

Upvotes: 0

JeffC
JeffC

Reputation: 25611

You can simplify your XPath to

//div[contains(.,'User Name')]/following::input[@type='text']

The following axis from MDN.

The following axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.

The other INPUTs are hidden so specifying @type='text' will find only the one you want.

Upvotes: 1

Related Questions