如何使用硒处理表格

时间:2018-12-03 09:32:27

标签: selenium

我在处理桌子时感到困惑 1.如何点击表格中的复选框 2.如何点击表格中的值 3,如何处理动态和静态表 4.如何计算表格中可用的行数和列数

enter image description here

2 个答案:

答案 0 :(得分:0)

  1. 如何处理动态和静态Web表。

随机检查表中的元素并复制XPATH,例如,我在一列但两行中包含2个元素的2 xpath

  1. [@id='hello']/tbody/tr[**2**]/td
  2. [@id='hello']/tody/tr[**3**]/td

这里2和3改变了休息,您必须将x路径分为2部分

String beforeXpath="[@id='hello']/tbody/tr[";
String afterXpath="]/td";

然后使用循环

for(int i=0;i<=here you can get size of rows using tag name;i++)
{
// with this you can click on any element or text 
driver.findElement(By.xpath(beforeXpath+i+afterXpath)).click(); 
}

如何获取行数:-

List<WebElement>list=driver.findElements(By.TagName("tr"));
System.out.println(list.getsize());

如何获取列数:-

List<WebElement>list1=driver.findElements(By.TagName("td"));
System.out.println(list1.getsize());

答案 1 :(得分:0)

最通用的方法是使用tagNametr值的td方法。

@Test 
public void testWebTable()  { 
    WebElement simpleTable = driver.findElement(By.xpath("//span[2]")); 

    // Get all rows 
    List<WebElement> rows = simpleTable.findElements(By.tagName("tr")); 

    // rows count assert and count 
    Assert.assertEquals(rows.size(),4); 
    System.out.println("Total Rows count in table" + rows.size());

    // Print data from each row 
    for (WebElement row : rows) { 
        List<WebElement> cols = row.findElements(By.tagName("td")); 

        // column count assert and count
        Assert.assertEquals(cols.size(),4); 
        System.out.println("Total Column count in each row" + cols.size());

        for (WebElement col : cols) {
            // to select specific column compare its text
             if (col.getText().equals("some text")) {
              col.click(); // assuming td contains check box or link
              col.sendKeys(); // assuming td contains text box
              }
            // print complete table data                 
             System.out.print(col.getText() + "\t"); 

           } System.out.println(); 
       }
    }

要单击,还必须在秒内使用WebElement进行单击。 要处理动态表,您必须使用xpath轴策略来定位元素 例如将xpath写入直到不变的静态列,然后使用xpath轴方法,例如previous,following,following sibling等。

相关问题