有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取一行中的列数<td>或<th>?

当我使用下面的代码段时,我想得到给定行中的列数

int size = element.findElement(By.xpath("/tr[" + Row + "]")).findElements(By.tagName("td")).size();

我得到一个异常,声明NoTouchElementException

下面是HTML块

<table class="DynamicOrderTable" id="customerOrderHeader">
<tbody>
    <tr style="background-color: rgb(246, 246, 246);">
        <th>Order Number</th>
        <th>Version</th>
        <th>Customer Name</th>
        <th>Order Status</th>
        <th>Order Sub-status</th>
    </tr>
    <tr class="Temp">
        <td class="close" id="orderNumber">
            <div class="clickableText">1234</div>
        </td>
        <td class="close">1</td>
        <td class="close" id="customerName">ABC101</td>
        <td title="OrderResponse Sequence Number:14" class="close" id="orderStatus"><div class="clickableText">Complete</div></td>
        <td class="close">Closed</td>
    </tr>
</tbody>
</table>

当我们有thead和tbody标签时,如何获得一行中的列数


共 (4) 个答案

  1. # 1 楼答案

    如果我正确理解了您的问题,下面的代码应该可以帮助您获得列数

    使用XPath

    int size = driver.findElements(By.xpath("//*[@id="customerOrderHeader"]/tbody/tr[1]/th")).size();
    

    使用CssSelector

    int size = driver.findElements(By.cssSelector("table#customerOrderHeader>tbody>tr:first-child>th")).size();
    
  2. # 2 楼答案

    获取列大小的代码是正确的,只需将/tr中的.//tr更改为xpath,如下所示:

    WebElement element = driver.findElement(By.id("customerOrderHeader"));
    
    int size = element.findElement(By.xpath(".//tr[" + Row + "]")).findElements(By.tagName("td")).size();
    

    int size = element.findElements(By.tagName("tr")).get(Row).findElements(By.tagName("td")).size();
    
  3. # 3 楼答案

    请尝试以下代码:

    int count =driver.findElements(By.xpath(".//tr[@class='Temp']//td")).size();
    System.out.println("count is "+count);//output is count is 5
    
  4. # 4 楼答案

    将cells属性与行索引一起使用

     document.getElementById("customerOrderHeader").rows[0].cells.length;