Follow the below C# code to retrieve data from a table. To demonstrate this I have used a table with id="accounts" in "http://developer.yahoo.com/yui/examples/datasource/datasource_table_to_array.html".
<table id="accounts">
<caption>Table in markup with data in it</caption>
<thead>
<tr>
<th>Due Date</th>
<th>Account Number</th>
<th>Quantity</th>
<th>Amount Due</th>
</tr>
</thead>
<tbody>
<tr>
<td>1/23/1999</td>
<td>29e8548592d8c82</td>
<td>12</td>
<td>$150.00</td>
</tr>
<tr>
<td>5/19/1999</td>
<td>83849</td>
<td>8</td>
<td>$60.00</td>
</tr>
...
</tbody>
</table>
Details of the code.
- Created a Web Element for of the By.XPath("//table[@id='accounts']/thead/tr")
- Created an IList with collection of all the tag web elements under the /thead/trBy.XPath("//table[@id='accounts']/thead/tr/th")
- Access the contents of the table head using a loop.
- Created a Web Element for of the By.XPath("//table[@id='accounts']/tbody/tr")
- Created a IList with collection of all the tag web elements under the /tbody/tr By.XPath("//table[@id='accounts']/tbody/tr/th")
- Access the contents of the table body using a loop.
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace BusinessCreation
{
class ExtractDataFromATable
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://developer.yahoo.com/yui/examples/datasource/datasource_table_to_array.html");
if(driver.FindElement(By.XPath("//table[@id='accounts']/thead/tr/th")).Displayed)
{
IWebElement webElementHead = driver.FindElement(By.XPath("//table[@id='accounts']/thead/tr"));
IList<IWebElement> ElementCollectionHead = webElementHead.FindElements(By.XPath("//table[@id='accounts']/thead/tr/th"));
foreach (IWebElement item in ElementCollectionHead)
{
Console.WriteLine(item.Text);
}
}
if (driver.FindElement(By.XPath("//table[@id='accounts']/tbody/tr")).Displayed)
{
IWebElement webElementBody = driver.FindElement(By.XPath("//table[@id='accounts']/tbody/tr"));
IList<IWebElement> ElementCollectionBody = webElementBody.FindElements(By.XPath("//table[@id='accounts']/tbody/tr"));
foreach (IWebElement item in ElementCollectionBody)
{
string []arr= new string[4];
arr = item.Text.Split(' ');
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
}
Console.ReadLine();
}
}
}
Awesome just found the perfect solution to the problem
ReplyDeletethank you very much cheryjose