0

I am trying to go through each DIV element, write some data and finally click submit. However, I am not sure why but writing the values and click the submit button is always on the same element.

for example:

<div id="random_id" class="section">
  Last name:<br>
  <input type="text" id="lastname"><br><br>
  <input type="submit" value="Submit" id="submit">
</div>

 <div id="random_id" class="section">
    Last name:<br>
    <input type="text" id="lastname"><br><br>
    <input type="submit" value="Submit" id="submit">
</div>

<div id="random_id" class="section">
    Last name:<br>
    <input type="text" id="lastname"><br><br>
    <input type="submit" value="Submit" id="submit">
</div>

<div id="random_id" class="section">
    Last name:<br>
    <input type="text" id="lastname"><br><br>
    <input type="submit" value="Submit" id="submit">
</div>

I wrote the following python script to loop all sections, fill data inside and click submit.

elements = driver.find_elements_by_xpath("//div[@class='section']")
for element in elements:
    element.find_element_by_xpath("//div[@id='section']").send_keys("hello world")
    element.find_element_by_xpath("//div[@id='submit']").click()

When I run the script, only the first element is filled and clicked for 3 times.

user1341970
  • 449
  • 2
  • 7
  • 15

1 Answers1

0

Only first element is filled, because when you use element.child_element with xpath in Selenium you have to add ./, child::tag or use descendant::tag to make it relative to parent, otherwise it's an absolute. You can find here.

element.find_element_by_xpath(".//input[@id='lastname']")
element.find_element_by_xpath("child::input[@id='lastname']")
element.find_element_by_xpath("descendant::input[@id='lastname']")

How to do with xpath:

elements = driver.find_elements_by_xpath("//div[@class='section']")
for element in elements:
    element.find_element_by_xpath(".//input[@id='lastname']").send_keys("hello world")
    element.find_element_by_xpath(".//input[@id='submit']").click()

How to do with css selector:

elements = driver.find_elements_by_css_selector(".section")
for element in elements:
    element.find_element_by_css_selector("#lastname").send_keys("hello world")
    element.find_element_by_css_selector("#submit").click()
Sers
  • 12,047
  • 2
  • 12
  • 31