XPATH: Inputting value for an unknown number of xpaths using .find_elements_by_xpath

Issue

I’ve done a lot of searching around for this, but it seems like I can only find the answers in .js . What I would like to do is through python use .find_elements_by_xpath , and having selected an unknown number of elements, input a value by iterating from top to bottom of relevant elements. It is important to know that there may be anywhere from 1+ number of elements that need to be filled.

Some have suggested this method in .js :

driver.findElements(By.xpath("<xpath>")).then(function(elem) {
    for(var i=0; i<elem.length; i++){
        driver.findElements(By.xpath("<xpath>")).get(i).sendKeys('some Text');
    }
});

I’m not skilled enough to translate that properly, but maybe it’ll give someone an idea for the solution.

Hopefully my intention is clear enough! Thanks everyone so much for your help.

Solution

This is how it will look like on Python. Code with comments:

from selenium.webdriver.common.by import By
from selenium import webdriver

website = "https://YOURWEBSITE.com"
driver = webdriver.Chrome(executable_path='YOUR/PATH/TO/chromedriver.exe')
driver.get(website)

# if you want to find all inputs on the page using XPATH and send there some value use:
all_inputs_on_the_page = driver.find_elements(By.XPATH, "//div//input")
for input in all_inputs_on_the_page:
    input.send_keys("TEXT_TO_INSERT")


# if you want to find some elements and after that - find some elements inside these elements then use:
divs_on_the_page = driver.find_elements(By.XPATH, "//div")
for div in divs_on_the_page:
    inputs_inside_a_div = div.find_elements(By.XPATH, ".//input")
    for input in inputs_inside_a_div:
        input.send_keys("TEXT_TO_INSERT")

Answered By – Andrey Kotov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published