简体   繁体   中英

How to handle web table in selenium c#

In my application, i have to assert name on the webtable but i am unable to do so.

Below is the image of my HTML code and i am unable to copy paste here.

在此处输入图像描述

I have to get the name:"Robert Brits" from the web table and want to assert the same.

I tried the below logic:

 IWebElement tableElement = driver.FindElement(By.Xpath("//table[@id='globalSearchTable']"));
            IList<IWebElement> tableRow = tableElement.FindElements(By.TagName("tr"));
            IList<IWebElement> rowTD;
            foreach (IWebElement row in tableRow)
            {
                rowTD = row.FindElements(By.TagName("td"));
                {
                  _____
                  }
             }

I'm not sure how to proceed further and complete the code. Could anyone help me? Thanks in advance

You could do something like this....

    var value = "Robert Brits";

    var table = driver.FindElement(By.Xpath("//table[@id='globalSearchTable']")
    foreach (var tr in table.FindElements(By.TagName("tr")))
    {
        var tds = tr.FindElements(By.TagName("td"));
        for (var i = 0; i < tds.Count; i++)
        {
           if (tds[i].Text.Trim().Contains(value))
         {
               var test = tds[i].Text.Trim();
                Assert.IsTrue(test.Contains(value));
                break;
         }

        }
    }

I know this looks odd with the conditional statement but I left it there for a reason. Most tables have many columns. So you may want the if statement to look for a name, account number, email etc. and stop. Then you may need to go to the left or right in that row to get text or click a link. In this example you could call tds[i] as the search criteria and then use tds[i-2] to go two columns to the left of tds[i] or use tds[i+3] to go three columns to the right of tds[i].

If you want to only verify that value try following xpath .

IWebElement tableElement = driver.FindElement(By.Xpath("//table[@id='globalSearchTable']/tbody/tr[1]/td[3]"));
Assert.AreEqual(tableElement.Text,"Robert Brits")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM