Selenium+Java元素定位之三

首先自己先准备一个表格代码:

<!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进行表格的元素定位,代码编写如下:

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()+"
");
                String text = td.getText();
                if(text.equals(str)){
                    System.out.print(text+"
");
                }
            }
        }
    }
}

以上代码可以将表格中内容为“2-1”的内容打印出来

原文地址:https://www.cnblogs.com/biyuting/p/8687044.html