0

I have table which have several <td> tags, again these tag have nested <div> tag. But the number of <div> are dynamic. Means, for each <td> tag number of <div> are different.

I wanted to find the total number of <div> inside a <td> and iterate them to grab each div's value.

I've tried using below xpath, but I'm not sure how can I get the count of <div>'s for loop through them.

for(int i=1;i<=NoOfDivs;i++) 
{
    WebElement NestedDivs= driver.findElement(By.xpath("/html/body/table[4]/tbody/
    tr[3]/td[2]/div["+i+"]"));
}

Webpage HTML is given in the below snap:

enter image description here

2 Answers 2

1

Use below method template to get the number of div.

public static int get_div_count_in_table(){
    String _xpath = "//table//td[td_no]/div" ; 
    List<WebElement> _divs = driver.findElements(By.xpath(_xpath)); 
    int NoOfDivs = _divs.size(); 
    return NoOfDivs; 
}

You might alter the code snippet as per your requirement, but the logic mostly will remain the same.

I have tried a similar problem in this page, to get the list of divs and it is returning the expected. Please see below the page and xpath.

enter image description here

enter image description here

The xpath returns 10 as the size. Check this and let us know if you are able to follow.

3
  • I tried this but it returns zero as _divs.size() Commented Jul 27, 2018 at 7:23
  • I have updated the answer itself to address your query as it needed to attach images. Hope this helps. Commented Jul 27, 2018 at 8:29
  • Strange,,i just removed all and re-write that piece of code & it worked. Commented Jul 27, 2018 at 8:56
2

Make sure you are locating the correct table. Based on information provide by you. Please refer the below code snippet to find all the <div> and iterate through.

List<WebElement> allElements = driver.findElements(By.xpath("//table[4]/tbody/tr[3]/td[2]/div"));
int totalDivs = allElements.size();
System.out.println("total divs :"+totalDivs)

for(WebElement element : allElements){
    System.out.println("Value :"+element.getText());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.