Find nearest / closest button Selenium
I'm working with selenium to auto-fill some <input>
on my site. I have multiple inputs that are identical, each with an input field and a submit button. I want to post a string in each input field and submit it (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 first take everything input
and then iterate over them The problem is that it fills every input but always clicks on the same button.
So my question is, how do I find the closest button?
I found this one , but if I want to use xpath
and following-sibling
, I will also need to select 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 an easy solution to find the closest item to the selected item?
source to share
You can use in.get_attribute('id')
to extract id
.
Alternatively, you can also select following-sibling::button
for a given element using XPath:
in.find_element_by_xpath(".//following-sibling::button").click()
Explanation:
-
.
- selects the current node (<input>
) -
//
- selection of nodes in the document-
following-sibling::button
- where siblings after the current node are<button>
-
source to share