首先本身先準備一個表格代碼:html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <table border = "1" align="center" width="400" height="200"> <tr> <td>1-1</td> <td>1-2</td> <td>1-3</td> </tr> <tr> <td>2-1</td> <td>2-2</td> <td>2-3</td> </tr> <tr> <td>3-1</td> <td>3-2</td> <td>3-3</td> </tr> </table> </body> </html>
使用Webdriver進行表格的元素定位,代碼編寫以下:
java
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.List; /** * Created by Administrator on 2018/4/1 0001. */ public class LocalTest02 { public static void main(String[] args){ String str = "2-1"; WebDriver driver; System.setProperty("webdriver.firefox.bin","D:\\ztsoft\\Firefox\\firefox.exe"); String url = "E:\\selenium\\table.html"; driver = new FirefoxDriver(); driver.get(url); //定位到table元素 WebElement table = driver.findElement(By.tagName("table")); //表格中有不少tr,只會查找第一個tr,findElement只能定位一個元素 table.findElement(By.tagName("tr")); //使用findElements,能夠查找一組元素,而後存儲在WebElement的數組中 List<WebElement> rows = table.findElements(By.tagName("tr")); //循環list取出tr的值 //for(int i = 0;i < rows.size();i++){} //循環list取出tr的值 for(WebElement row:rows){ List<WebElement> tds = row.findElements(By.tagName("td")); for(WebElement td:tds){ //System.out.print(td.getText()+"\n"); String text = td.getText(); if(text.equals(str)){ System.out.print(text+"\n"); } } } } }
以上代碼能夠將表格中內容爲「2-1」的內容打印出來web