3

Im working with selenium to automatically fill out some <input>s on my site. I have multiple inputs which are identical, each with an input field and a send button. I want to post a string in each input field and send it (the site does not reload).

input = driver.find_elements_by_class_name('cdRecord')
for in in inputs:
    in.click()
    nr = str(randint(0, 1000))
    in.send_keys("..."+nr)
    NEXT_BUTTON_XPATH = '//button[@type="submit" and @title="next"]' #this does not work
    driver.find_element_by_xpath(NEXT_BUTTON_XPATH).click()

I fetch all the input first and then iterate over them. The problem is that he fills out each input but always clicks the same button.

So my Question is, how do I find the closest button?

I found this but if I want to use the xpath and following-sibling I also would need to fetch some id and change the path in each iteration like:

x = fetch id from the input field?
driver.find_element_by_xpath("//input[@id, "x"]/following-sibling::button")

Is there a simple solution to find the closest element to the chosen element?

hansTheFranz
  • 2,511
  • 4
  • 19
  • 35

1 Answers1

2

You can use in.get_attribute('id') to retrieve the id.


Alternatively, you can also select the following-sibling::button of a given element using an XPath:

in.find_element_by_xpath(".//following-sibling::button").click()

Explanation:

  • . - Selects the current node (<input>)
  • // - Selects nodes in the document
    • following-sibling::button - where siblings after the current node is a <button>

Reference: https://www.w3schools.com/xml/xpath_intro.asp

budi
  • 6,351
  • 10
  • 55
  • 80