I'm working in C# selenium and I want to grab a certain column from a web table for testing. I'm curious if you can use
row.FindElements(By.TagName("wanted_col_name"));
to grab a certain column by name or to grab it by the column number
I specifically want to grab the elements from product line, combine them with part number and then put the strings into an array. An example of this output would be
BCA/A1
BCA/A2
PEN/30
Of course, the DELIVERED BY NOON
, but I don't know how to exclude it.
The code I have right now prints out every element of the table, but doesn't work when I try to print out only the column I want as it includes the entire row in a single string and the DELIVERED BY NOON
string.
IWebElement tableElement = driver.FindElement(By.XPath("//*[@id='InvoiceTable']/tbody"));
IList<IWebElement> tableRow = tableElement.FindElements(By.TagName("tr"));
IList<IWebElement> rowTD;
foreach(IWebElement row in tableRow)
{
rowTD = row.FindElements(By.TagName("td"));
foreach (IWebElement col in rowTD)
{
TestContext.WriteLine(col.Text + " ... \n\n");
}
}
This code does what you want for a W3C website about HTML tables, tested and working:
driver.Navigate().GoToUrl("https://www.w3schools.com/html/html_tables.asp");
var table = driver.FindElement(By.Id("customers"));
var rows = table.FindElements(By.TagName("tr"));
foreach (var row in rows)
{
var tds= row.FindElements(By.TagName("td"));
if (tds.Count > 2)
Console.WriteLine("{0}/{1}", tds[0].Text, tds[2].Text);
}
It works by selecting the customers table and then it concatenates the first column's text with the 3rd column in same format as your example.
I've added a check for tds.Count in the foreach loop because the first tablerow in the W3C demo page has a table header, so it returns 0 tds.
I hope this helps.