how to loop through a table in selenium?

Shashank.M picture Shashank.M · Jul 31, 2016 · Viewed 7.2k times · Source

I am new to selenium and I have this question where I need to loop through a table and get the values in that table

I wanted to know how to loop the table so i can get a contracts that's the " PILOT TRAVEL CENTE-122194-W/S - UNB Contract","PILOT TRAVEL CENTE-122194-W/S - UNB Fwrd Cont" and "UNB Spot" along with the data of the table also. Thanks in advance.

Answer

Leon Barkan picture Leon Barkan · Jul 31, 2016

Ok you didn't say nothing about the language you use so i will give you example in C#

//Init table element (in this case by tag name but better chose by id or Name)
IWebElement tableElement = driver.FindElement(By.TagName("table"));

//Init TR elements from table we found into list
IList<IWebElement> trCollection = tableElement.FindElements(By.TagName("tr"));
//define TD elements collection.
IList<IWebElement> tdCollection;

//loop every row in the table and init the columns to list
foreach(IWebElement element in trCollection)
{
   tdCollection = element.FindElements(By.TagName("td"));

   //now in the List you have all the columns of the row
   string column1 = tdCollection[0].Text;
   string column2 = tdCollection[1].Text;
   ...
}

if you use other language just change the syntax the logic is the same.