Sumeet Fortune
Sumeet Fortune

Reputation: 41

How to access a specific row from web table

I'm trying to select a specific row having class name as 'topicRow post' from the table given below

Code on website

<table class="content" width="100%">
<tbody>
    <tr class="topicTitle">
    <tr class="topicSubTitle">
    <tr class="topicRow post">
    <tr class="topicRow_Alt post_alt">
    <tr class="topicRow post">
    <tr class="topicRow_Alt post_alt">
    <tr id="forum_ctl03_ctl00" class="header2">
    <tr class="post">
    <tr>
</tbody>
</table>

Selenium code

WebElement Webtable=driver.findElement(By.xpath("//*[@class='content']"));
List<WebElement> TotalRowCount=Webtable.findElements(By.xpath("//*[@class='content']/tbody/tr[contains(@class,'topicRow post')]"));
System.out.println("No. of Rows in the WebTable: "+TotalRowCount.size());

Problem

Every time it prints the size of all the rows present in table. Please guide...

Upvotes: 3

Views: 216

Answers (3)

yong
yong

Reputation: 13712

In your code, you had already use Webtable to find rows, but you still repeat the xpath portion "//*[@class='content']" for Webtable in the Webtable.findElements().

Change your code as below:

List<WebElement> TotalRowCount=Webtable.
    findElements(By.xpath(".//tr[contains(@class,'topicRow post')]"));

Or change to use driver.findElements() with repeated xpath portion:

List<WebElement> TotalRowCount=driver.
     findElements(By.xpath("//*
      [@class='content']/tbody/tr[contains(@class,'topicRow post')]"));

If above two ways don't work as expected, try below code:

WebElement table = driver.findElement(By.css("table.content"));
List<WebElement> foundRows = table.findElements(By.css("tr.topicRow.post"));
System.out.println("Found rows count: "+ foundRows.size());

Upvotes: 2

Sumeet Fortune
Sumeet Fortune

Reputation: 41

Use thread.sleep() Here is the code

Thread.sleep(5000);
List<WebElement> TotalRowCount = driver.findElements(By.xpath("//*[@class='content']/tbody/tr[contains(@class,'topicRow post')]")); 

System.out.println("No. of Rows in the WebTable: "+TotalRowCount.size());

Upvotes: 1

Guy
Guy

Reputation: 50809

You can give an index, 1 for the first match and 2 for the second

Webtable.findElements(By.xpath("//*[@class='content']/tbody/tr[contains(@class,'topicRow post')][1]"));

Upvotes: 1

Related Questions