WebDriver獲得表格里所有單元格的文本

jopen 11年前發布 | 78K 次閱讀 Selenium 測試工具 webdriver

方法為:

1. 得到表格中所有的tr,存到list到中

2.對tr進行循環,根據當前的tr,得到當前所有td的集合存到list當中

3.循環中所有td里的文本 

具體實現為

    package com.example.tests;  
    import static org.junit.Assert.*;  
    import java.util.*;  
    import org.junit.*;  
    import org.openqa.selenium.*;  
    import org.openqa.selenium.ie.InternetExplorerDriver;  
    public class Selenium2 {  
        WebDriver driver = new InternetExplorerDriver();  
        JavascriptExecutor jse = (JavascriptExecutor)driver;  
        @Test  
        public void tableTest() {     
            driver.get("http://www.w3school.com.cn/html/html_tables.asp");     
            //首先得到所有tr的集合  
            List<WebElement> rows = driver.findElements(By.cssSelector(".dataintable tr"));   
            //驗證表格的行數  
            assertEquals(11,rows.size());  
             //打印出所有單元格的數據  
            for (WebElement row : rows) {   
                //得到當前tr里td的集合  
                List<WebElement> cols =  row.findElements(By.tagName("td"));   
                for (WebElement col : cols) {  
                    System.out.print(col.getText());//得到td里的文本  
                }  
                System.out.println();  
            }  
            driver.close();  
        }  
    }  
打印結果為

---------------------------------------------------------------------------------

<table>定義表格
<caption>定義表格標題。
<th>定義表格的表頭。
<tr>定義表格的行。
<td>定義表格單元。
<thead>定義表格的頁眉。
<tbody>定義表格的主體。
<tfoot>定義表格的頁腳。
<col>定義用于表格列的屬性。
<colgroup>定義表格列的組。

 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!