Reputation: 169
I have a HTML in the formal of this
<tbody>
<tr>
<td> Test1 </td>
<td> .. </td>
<tr/>
<tr> ... </tr>
</tbody>
<tbody>
<tr>
<td> Test2 </td>
<td> .. </td>
<tr/>
<tr> .. </tr>
</tbody>
<tbody>
<tr>
<td> Test3 </td>
<td> .. </td>
<tr/>
<tr> .. </tr>
</tbody>
I need to have a list of strings Test1, Test2, Test3. I am not quite sure how to iterate through all the tbody's and go in the tr and get the correct td. Could someone point me in the correct direction? How could I generate the xpath into those particular element? They do not have any ids
I was looking into webDriver.findElements(). Could you I use this to iterate through the tbody? If so how?
I tried to do the following:
driver = new FirefoxDriver();
driver.get(..);
WebElement telem = driver.findElement(By.cssSelector("td"));
List<WebElement> tr_collection=telem.findElements(By.cssSelector("td"));
This doesn't seem to get all the Test1, Test2, Test3 strings. Unfortunately the HTML doesnt have IDs that I can use. How could I iterate through all these?
Upvotes: 2
Views: 1702
Reputation: 3004
try the below code:
String text = null;
List<WebElement> allElements = driver.findElements(By.xpath("//td[contains(text(),'Test')]"));
for(WebElement element: allElements){
text= element.getText();
System.out.println("Text is : "+text);
}
hope this will help you.
Upvotes: 0
Reputation: 466
Same as Ranjith's, but with Java 8 and xPath:
List<String> inOneStatement = driver.findElements(By.xpath("//tbody/tr[1]/td[1]")) //List<WebElement> that contains 3 td that hold the desired strings
.stream().map(WebElement::getText) //accumulate the outputs from getText of each of those elements
.collect(Collectors.toList()); // return them as List<String>
Sorry, didn't check the code in IDE, could have errors.
NB: I would never use this xPath locator in actual test framework, but to build a better one we need more context (full page source).
Upvotes: 1
Reputation: 4730
Solution for this is:
List<String> actualValues = new ArrayList<>();
List<WebElement> tableRowsList = driver.findElements(By.cssSelector("tbody > tr"));
for(WebElement ele: tableRowsList) {
actualValues.add(ele.findElement(By.cssSelector("td:nth-of-type(1)").getText()));
}
Upvotes: 1