runningman
runningman

Reputation: 11

Looping through table using selenium (c#)

I have a problem of filling in this dictionary with a result from HTML table. HTML looks something like this:

  <td class="name">
     <span data-bind="text:'hierarchyId'"></span>
     <span data-bind="text:'name'"></span> 
   </td>

I want to fill in dictionary with HiearchyId and name for every td, but it ends up filling only first column and in second iteration return error that same ID already exist in dictionary. Please advice.

  public Dictionary<string,string> ListOfSections()
    {
        Dictionary<string,string> newDictionary = new Dictionary<string,string>();
        IList<IWebElement> tdSectionName = sectionTable.FindElements(By.XPath("//td[@class='name']"));
        foreach (IWebElement element in tdSectionName)
        {
            IWebElement hierarchy = element.FindElement(By.XPath("//span[@data-bind='text: hierarchyId']"));
            IWebElement name = element.FindElement(By.XPath("//span[@data-bind='text: Name']"));
            newDictionary.Add(hierarchy.Text, name.Text);
        }
        return newDictionary;
    }

Upvotes: 1

Views: 719

Answers (1)

Sers
Sers

Reputation: 12255

Add .// to xpath to get child element like below, or use css selector:

public Dictionary<string,string> ListOfSections()
{
    Dictionary<string,string> newDictionary = new Dictionary<string,string>();
    IList<IWebElement> tdSectionName = sectionTable.FindElements(By.XPath("//td[@class='name']"));
    foreach (IWebElement element in tdName)
    {
        IWebElement hierarchy = element.FindElement(By.XPath(".//span[@data-bind='text: hierarchyId']"));
        IWebElement name = element.FindElement(By.XPath(".//span[@data-bind='text: Name']"));
        newDictionary.Add(hierarchy.Text, name.Text);
    }
    return newDictionary;
}

Css selector:

public Dictionary<string,string> ListOfSections()
{
    Dictionary<string,string> newDictionary = new Dictionary<string,string>();
    IList<IWebElement> tdSectionName = sectionTable.FindElements(By.CssSelector("td.name"));
    foreach (IWebElement element in tdName)
    {
        IWebElement hierarchy = element.FindElement(By.CssSelector("span[data-bind='text: hierarchyId']"));
        IWebElement name = element.FindElement(By.CssSelector("span[data-bind='text: Name']"));
        newDictionary.Add(hierarchy.Text, name.Text);
    }
    return newDictionary;
}

Upvotes: 2

Related Questions