- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.WebElement;
- import org.testng.annotations.Test;
- public class LocateTable {
- public WebDriver driver;
- @Test
- public void LocateTableTest() {
- WebElement table = driver.findElement(By.id("table"));
- List<WebElement> rows = table.findElements(By.tagName("tr"));
- // assertEquals(5,rows.size());
- for(WebElement row:rows){
- List<WebElement> cols= row.findElements(By.tagName("td"));
- for(WebElement col:cols){
- System.out.println(col.getText()+"\t");
- }
- System.out.println("");
- }
- }
- }
代碼邏輯:
(1)先定位表格的頁面元素對象;
- WebElement table = driver.findElement(By.id("table"));
- List<WebElement> rows = table.findElements(By.tagName("tr"));
(3)使用for循環方式,先將表格行對象從rows對象中取出,使用findElements函數將表格行對象中的所有單元格對象存儲到名爲cols的List對象中,然後再次使用for循環把每行的單元格文本遍歷輸出。
- List<WebElement> rows = table.findElements(By.tagName("tr"));
- for(WebElement row:rows){
- List<WebElement> cols= row.findElements(By.tagName("td"));
- for(WebElement col:cols){
- System.out.println(col.getText()+"\t");
- }
- System.out.println("");
- }
col.getText()表示獲取單元格的文本內容
- <pre name="code" class="java"># 定位顯示錶格的第二行第二列單元格
- XPath表達式實例:
- //*[@id='table']/tbody/tr[2]/td[2]
- Java實例代碼:
- WebElement cell = driver.findElement(By.xpath("//*[@id='table']/tbody/tr[2]/td[2]"));
- 表達式中的tr[2]表示第二行,td[2]表示第二列,組合起來就是第二行第二列單元格