Vinicius Kostriuba Vinicius Kostriuba - 1 month ago 12
Java Question

How to get multiple elements (div) using Xpath Selenium WebDriver JAVA?

I'm having some difficulties to get multiple elements from a div.
As you can see, I got the div[1] and after that I want to get more 8 div inside div[1]. But I want to do that with xpath(same line). Anyone have some idea?

Father =

.//*[@id='result']/div[1]


Sons =

.//*[@id='result']/div[1]/div[6]
.//*[@id='result']/div[1]/div[9]
.//*[@id='result']/div[1]/div[12]
.//*[@id='result']/div[1]/div[15]
.//*[@id='result']/div[1]/div[18]
.//*[@id='result']/div[1]/div[21]
.//*[@id='result']/div[1]/div[24]
.//*[@id='result']/div[1]/div[27]


My Code:

List<String> productName = new ArrayList<String>();
List<WebElement> allProductsName = driver.findElements(
By.xpath(".//*[@id='result']/div[1]/div[6]"));
for(WebElement w : allProductsName) {
productName.add(w.getText());
}
System.out.print(productName);


I imagined something like that
".//*[@id='result']/div[1]/div[6],[9]..."
or

".//*[@id='result']/div[1]/div[6 and 9 ....]"


But didn't work.

Answer

as your product description comes in 6,9,12,15,18 use this code that will iterate through 6 to 27 in multiplication of 3.

List<String> productName = new ArrayList<String>();


for(int i=6; i<=27; i=i+3)
{

    List<WebElement> allProductsName = driver.findElements(By.xpath(".//*[@id='result']/div[1]/div["+i+"]"));
    for(WebElement w : allProductsName) {
        productName.add(w.getText());
    }
}
System.out.print(productName);
Comments