Arnab
Arnab

Reputation: 271

How to get the exact number of rows in webtable using xpath in webdriver 2 using C#

Want to fetch the number of rows present in the table Xpath I am passing is .//*[@id='ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory']

My Page HTML is like

<table id="ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory"
<tbody>
   <tr>
      <th></th>
      <th></th>
      <th></th>
   </tr>
   <tr>
      <td></td>
      <td></td>
      <td></td>
   </tr>
   <tr>
      <td></td>
      <td></td>
      <td></td>
   </tr>
   <tr>
      <td></td>
      <td></td>
      <td></td>
   </tr>
</tbody>
</table>

my code is returning 0 as out put.

IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
IList<IWebElement> ElementCollectionHead = TargetElement.FindElements(By.XPath(xPathVal+"/tbody/tr[*]"));        
int RowCount = ElementCollectionHead.Count;

Upvotes: 1

Views: 4327

Answers (2)

Arnab
Arnab

Reputation: 271

Previously i was using

IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
IList<IWebElement> ElementCollectionHead = TargetElement.FindElements(By.XPath(xPathVal+"/tbody/tr[*]"));        
int RowCount = ElementCollectionHead.Count; 

The problem was in 2nd line.It should be like:

IList<IWebElement> ElementCollectionHead = driver.FindElements(By.XPath(xPathVal + "/tbody/tr[*]"));

Dont know why 1st was not working.If some one can then i will be thankful.

Upvotes: 0

Saifur
Saifur

Reputation: 16201

Two possible reasons of this issue can be as follows:

  1. Selenium needs some time to identify the element(element load time)
  2. The elements are inside the iframe as mentioned by @Richard.

The solution of first problem is probably to use Explicit wait with the FindElement() (Just as a side note, I would prefer CssSelector over XPath here since I do not have to use XPath)

By css = By.CssSelector("#ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory tr");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IList<IWebElement> elementCollectionHead = wait.Until(webDriver => webDriver.FindElements(css));
int rowCount = elementCollectionHead.Count;

If the issue is an iframe then you have to use SwitchTo() in order to switch to the iframe and then look for elements

// you can use xpath or cssselector to identify the iframe
driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe id")));

By css = By.CssSelector("#ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory tr");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));

IList<IWebElement> elementCollectionHead = wait.Until(webDriver => webDriver.FindElements(css));
int rowCount = elementCollectionHead.Count;

driver.SwitchTo().DefaultContent();

Upvotes: 1

Related Questions