WebDriver表格定位-----遍歷表格的全部單元格


  1. import org.openqa.selenium.By;  
  2. import org.openqa.selenium.WebDriver;  
  3. import org.openqa.selenium.WebElement;  
  4. import org.testng.annotations.Test;  
  5.   
  6. public class LocateTable {  
  7.     public WebDriver driver;  
  8.   @Test  
  9.   public void LocateTableTest() {  
  10.       WebElement table = driver.findElement(By.id("table"));  
  11.       List<WebElement> rows = table.findElements(By.tagName("tr"));  
  12. //    assertEquals(5,rows.size());  
  13.       for(WebElement row:rows){  
  14.           List<WebElement> cols= row.findElements(By.tagName("td"));  
  15.           for(WebElement col:cols){  
  16.               System.out.println(col.getText()+"\t");               
  17.           }  
  18.           System.out.println("");  
  19.       }  
  20.   }  
  21. }  

代碼邏輯:

(1)先定位表格的頁面元素對象;

[java] view plain copy
  1. WebElement table = driver.findElement(By.id("table"));  
(2)在表格頁面元素對象中,把所有的tr元素對象存儲到list對象中(即把表格中每行的對象存儲到一個list中)

[java] view plain copy
  1. List<WebElement> rows = table.findElements(By.tagName("tr"));  

(3)使用for循環方式,先將表格行對象從rows對象中取出,使用findElements函數將表格行對象中的所有單元格對象存儲到名爲cols的List對象中,然後再次使用for循環把每行的單元格文本遍歷輸出。

[java] view plain copy
  1. List<WebElement> rows = table.findElements(By.tagName("tr"));  
  2. for(WebElement row:rows){  
  3.  List<WebElement> cols= row.findElements(By.tagName("td"));  
  4.  for(WebElement col:cols){  
  5.   System.out.println(col.getText()+"\t");               
  6.  }  
  7.  System.out.println("");  
  8. }  

col.getText()表示獲取單元格的文本內容


  1. <pre name="code" class="java"># 定位顯示錶格的第二行第二列單元格  
  2. XPath表達式實例:  
  3.  //*[@id='table']/tbody/tr[2]/td[2]  
  4.  Java實例代碼:  
  5.  WebElement cell = driver.findElement(By.xpath("//*[@id='table']/tbody/tr[2]/td[2]"));  
  6.   
  7.  表達式中的tr[2]表示第二行,td[2]表示第二列,組合起來就是第二行第二列單元格  
http://toolsqa.com/selenium-webdriver/handle-dynamic-webtables-in-selenium-webdriver/
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章