简体   繁体   English

Selenium Webdriver - 获取表数据

[英]Selenium Webdriver - Fetching Table Data

I want to fetch data from tables in UI.我想从 UI 中的表中获取数据。 I know about looping through rows and columns using "tr" and "td".我知道使用“tr”和“td”循环遍历行和列。 But the one the table I have is something like this:但是我的桌子是这样的:

<table>
 <tbody>
  <tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
  <tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
  <tr><td>data</td><th>data</th><td>data</td><td>data</td></tr>
 </tbody>
</table>

How can I make my code generic, so that the occurrence of "TH" in middle can be handled.如何使我的代码通用,以便可以处理中间出现的“TH”。 Currently, I am using this code :目前,我正在使用此代码:

// Grab the table
WebElement table = driver.findElement(By.id(searchResultsGrid));

// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
 List<WebElement> cells = row.findElements(By.tagName("td"));
 for (WebElement cell : cells) {
 // And so on
 }
}

You could look for all children of tr element without differentiating between td and th.您可以在不区分 td 和 th 的情况下查找 tr 元素的所有子元素。 So instead of所以代替

List<WebElement> cells = row.findElements(By.tagName("td"));

I would use我会用

List<WebElement> cells = row.findElements(By.xpath("./*"));

Mayby 对于这个问题的所有者来说为时已晚,但对其他人有帮助。

List<WebElement> cells = row.findElements(By.xpath(".//*[local-name(.)='th' or local-name(.)='td']"));
// Grab the table
WebElement table = driver.findElement(By.id("searchResultsGrid"));

// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
    List<WebElement> cells = row.findElements(By.tagName("td"));
    for (WebElement cell : cells) {
        System.out.println("content >>   " + cell.getText());
    }
}

using cell.getText() would simply work使用cell.getText()会简单地工作

You don't need to loop through elements.您不需要遍历元素。 Instead, use a ByChained locator.相反,使用 ByChained 定位器。

If you table looks like this:如果你的表看起来像这样:

<table>
  <tbody>
    <tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
    <tr><td>data</td><td>data</td><td>data</td></tr>
    <tr><td>data</td><td>data</td><td>data</td></tr>
    <tr><td>data</td><td>data</td><td>data</td></tr>
  </tbody>
</table>

The locate like this:定位是这样的:

By tableBodyLocator = By.xpath(".//table/tbody");
By headerRowLocator = By.xpath(".//tr[position()=1]");
By dataRowsLocator = By.xpath(".//tr[not(position()=1)]");

By headerRowLocator = new ByChained(tableBodyLocator, headerRowLocator);
List<WebElement> weHeaders = driver.findElement(headerRowLocator)
       .findElements(By.xpath(".//th");
List<WebElement> allRowData = driver.findElements(tableBodyLocator, dataRowsLocator);

WebElement row1Data = allRowData.get(0);
WebElement row2Data = allRowData.get(1);

etc.

是的,它适用于带有硒的 c#...

IList<IWebElement> cells = row.findElements(By.xpath(".//*[local-name(.)='th' or local-name(.)='td']"));
IWebElement table = driver.FindElement(By.Id("id"));
List<IWebElement> allRows = new List<IWebElement> (table.FindElements(By.TagName("tr")));

foreach (var Row in allRows)
{
    List<IWebElement> cells = new List<IWebElement>( Row.FindElements(By.TagName("td")));
    foreach (var cel in cells)
    {
        string test = cel.Text;
    }
}

The below code you can not only get the rows and columns of the table but also you can get the order in which they are in the Browser,this is mainly handy if you have a nested structures in the TD column as in your case.下面的代码不仅可以获取表的行和列,还可以获取它们在浏览器中的顺序,如果像您的情况一样在 TD 列中有嵌套结构,这主要是方便的。

 public DataTable StoreHtmlTableToDataTable(IWebElement tblObj,bool isFirstRowHeader = true)
        {
            DataTable dataTbl = new DataTable();
            int rowIndex = 0;

            try
            {               
                //_tblDataCollection = new List<TableDataCollection>();

                var tblRows = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].rows; ", tblObj);

                if (tblRows != null)
                {
                    //Iterate through each row of the table
                    foreach (IWebElement tr in (IEnumerable)tblRows)
                    {                        
                        int colIndx = 0;
                        DataRow dtRow =  dataTbl.NewRow();
                        // Iterate through each cell of the table row
                        var tblCols = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].cells; ", tr);
                        foreach (IWebElement td in (IEnumerable)tblCols)
                        {
                            //add the header row of the table as  the datatable column hader row
                            if (rowIndex == 0)
                            {
                                dataTbl.Columns.Add("Col" + colIndx.ToString(), typeof(string));
                            }

                            dtRow["Col"+colIndx.ToString()] = td.Text;

                            //loop through any child or nested table structures if you want using the same approach for example links,radio buttons etc inside the cell

                            //Write Table to List : This part is not done yet                           
                            colIndx++;
                        }
                        dataTbl.Rows.Add(dtRow);
                        rowIndex++;
                    }

                }


            }
            catch (Exception)
            {
                throw;
            }

            //if first row is the header row then assign it as a header of the datatable
            if (isFirstRowHeader)
            {
                dataTbl = this.AssignDataTableHeader(dataTbl);
            }

            return dataTbl;
        }

TableDriver ( https://github.com/jkindwall/TableDriver.Java ) supports cells with both td and th tags. TableDriver ( https://github.com/jkindwall/TableDriver.Java ) 支持带有 td 和 th 标签的单元格。 Using TableDriver with your example table would look something like this:将 TableDriver 与您的示例表一起使用将如下所示:

Table table = Table.createWithNoHeaders(driver.findElement(By.id(searchResultsGrid), 0);
List<TableRow> allRows = table.getRows();
for (TableRow row : allRows) {
    List<TableCell> cells = row.getCells();
    for (TableCell cell : cells) {
        // Access the cell's WebElement like this: cell.getElement()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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