Search code examples
pythonseleniumxpathinput-field

python selenium selecting the correct input field


I am trying to select the correct input field to add a value to it. My current code partially works and it only selects to the first input field but I want to be able to manage which field I want to select and add here is what the web structure looks like

<tr role="row" class="tester odd">
  <td class="hidden"></td>
  <td class="hidden">222</td>
  <td class="rester-table-cell">
    <input type="hidden" name="building[0].model" value="PeterAVE">
    <input type="text" name="building[0].size" class="control-input-num">
  </td>
  <td class="soreted_1" data-search="PeterAVE" data-order="PeterAVE">    
    <a href="/resilisting/p/PeterAVE">PeterAVE</a> 
  </td>
</tr>
<tr role="row" class="tester even">
  <td class="hidden"></td>
  <td class="hidden">333</td>
  <td class="rester-table-cell">
    <input type="hidden" name="building[1].model" value="Sterling">
    <input type="text" name="building[1].size" class="control-input-num">
  </td>
  <td class="sorted_1" data-search="Sterling" data-order="Sterling">
    <a href="/resilisting/p/Sterling">Sterling</a>
  </td>
</tr>

I am selecting my input field based on values [PeterAVE,Sterling, etc...] currently my code is only selecting and filling the input field for PeterAVE since it's the first one and there are hundreds that I want to be able to choose.

Here is the code I am using.

driver.find_element_by_xpath("//input[contains(@class,'control-input-num')] ").send_keys("1")

I really appreciate any help.


Solution

  • You can find all the input fields with

    input_fields = driver.find_elements_by_class_name('control-input-num')
    

    and then select required by index

    input_fields[10].send_keys('1')
    

    You can also select input field by the value of preceding hidden input:

    driver.find_element_by_xpath("//input[@value='Sterling']/following-sibling::input[@class='control-input-num']").send_keys("1")