简体   繁体   中英

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.

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);

Just remove the index number at the end of the xpath and get all the immediate child divs in a List.

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

        System.out.print(productName);

The first thing I see is that the development of the application should not have duplicate static ID. If used like this, should be a class instead.

Second thing is, the xpath expression is not good approach. Try to never use //* , and you don't need the dot (.//), as it can take much longer to find the element(s), and make tests slower.

You don't show any html code, but based on your sample you should be able to get all div element using

List<WebElement> results = driver.getElements(By.id("result"));

or if you insist on xpath

List<WebElement> results = driver.getElements(By.xpath("//div[@id='result']"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM