如何从页面上的以下HTML中选择表格中的行数(注意:页面中有多个表格)。我试过下面的脚本,但它显示"此表中的行数= 0"。谢谢你的帮助。
HTML:
<table summary="" style="margin-top: 0px;">
<thead>
<tr>
<th id="yui-dt0-th-name" rowspan="1" colspan="1" class="yui-dt-first yui-dt-last">Advertiser
</th>
</tr>
</thead>
<tbody class="yui-dt-message" style="display: none;">
<tr class="yui-dt-first yui-dt-last">
<td colspan="1" class="yui-dt-first yui-dt-last">
<div class="yui-dt-liner yui-dt-loading">Loading...</div>
</td>
</tr>
</tbody>
<tbody tabindex="0" class="yui-dt-data" style="">
<tr style="" id="yui-rec0" class="yui-dt-first yui-dt-even">
<td headers="yui-dt0-th-name " class="yui-dt0-col-name yui-dt-col-name yui-dt-asc yui-dt-sortable yui-dt-first yui-dt-last">
<div class="yui-dt-liner">FirstName</div>
</td>
</tr>
<tr style="" id="yui-rec1" class="yui-dt-odd">
<td headers="yui-dt0-th-name " class="yui-dt0-col-name yui-dt-col-name yui-dt-asc yui-dt-sortable yui-dt-first yui-dt-last">
<div class="yui-dt-liner">SecondName</div>
</td>
</tr>
<tr style="" id="yui-rec2" class="yui-dt-even">
<td headers="yui-dt0-th-name " class="yui-dt0-col-name yui-dt-col-name yui-dt-asc yui-dt-sortable yui-dt-first yui-dt-last">
<div class="yui-dt-liner">ThirdName</div>
</td>
</tr>
<tr style="" id="yui-rec3" class="yui-dt-odd">
<td headers="yui-dt0-th-name " class="yui-dt0-col-name yui-dt-col-name yui-dt-asc yui-dt-sortable yui-dt-first yui-dt-last">
<div class="yui-dt-liner">FourthName</div>
</td>
</tr>
<tr style="" id="yui-rec4" class="yui-dt-last yui-dt-even">
<td headers="yui-dt0-th-name " class="yui-dt0-col-name yui-dt-col-name yui-dt-asc yui-dt-sortable yui-dt-first yui-dt-last">
<div class="yui-dt-liner">FifthName</div>
</td>
</tr>
</tbody>
</table>
我的剧本:
WebElement table_element = driver.findElement(By.tagName("tbody"));
List<WebElement> tr_collection=table_element.findElements(By.className("yui-dt-data"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = " +tr_collection.size());
答案 0 :(得分:0)
尝试使用以下代码获取表格中的行数(包括列标题):
List<WebElement> table_rows = driver.findElements(By.xpath("//table[@summary='']//tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+table_rows.size());
注意:假设您的网页中只有一个表
等待10秒,找到"tr"
的所有 'table'
标记元素,其中'td' tag
具有精确的innerHTML / text为&#39; FirstName&#39;。
try{
WebDriverWait wait = new WebDriverWait(driver, 10); //waiting for 10 seconds so the table is visible
List<WebElement> table_rows= wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[.='FirstName']/ancestor::table//tr")));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+table_rows.size());
}catch(Throwable e){
System.err.println("Error while getting the table. "+e.getMessage());
}