TestNg Selenium-动态查找表列值

问题描述 投票:1回答:3

我正在寻找一种使用testng和selenium动态获取列值的方法。我有2个表格,用于显示帐户ID,帐户名称,余额,可用余额等帐户详细信息。表1用于储蓄账户,表2用于贷款账户。表中有余额和可用余额列,但列位置不同。

我想要一个接受帐户id作为参数的方法(例如:id2),并返回相应帐户的余额?例如:如果我传递id2它应该返回500,如果我传递id4它应该返回500.注意:余额和可用余额始终是表的最后一列。

<table id=”savings”>
<thead>
<tr>
<th>id</th>
<th>balance</th>
<th>available balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>id1</td>
<td>100</td>
<td>123</td>
</tr>

<tr>
<td>id2</td>
<td>500</td>
<td>510</td>
</tr>

</tbody>
</table>






<table id=”loan”>
<thead>
<tr>
<th>id</th>
<th>description</th>
<th>nextpayment</th>
<th>balance</th>
<th>available balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>id3</td>
<td>first account</td>
<td>2018-09-21</td>
<td>100</td>
<td>123</td>
</tr>

<tr>
<td>id4</td>
<td>second account</td>
<td>2018-10-25</td>
<td>500</td>
<td>510</td>
</tr>

</tbody>
</table>
java selenium selenium-webdriver testng
3个回答
1
投票

enter image description here

首先,您可以使用id识别td,并使用id元素,您可以通过这种方式识别父元素,您将获得使用唯一ID标识的完整行。示例XPath://tr[.//td[contains(text(),'id2')]]/tr //tr[.//td[contains(text(),'id4')]]/tr

样本方法将为您提供余额和可用余额:

 // Pass Id value as id1, id2 , id3, or id4
public void finddetailByID(String id)
{
    List <WebElement> tablerows= driver.findElements(By.xpath("//tr[.//td[contains(text(),'"+id+"')]]/td"));
    int rowsize=tablerows.size();
    String availabebalance=tablerows.get(rowsize).getText();
    String balance=tablerows.get(rowsize-1).getText();
} 

0
投票

从id ='savings'的表中获取值单元格

    System.setProperty("webdriver.chrome.driver", "E:\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();

    driver.get("http://somethingURL");
    driver.manage().window().maximize();

    //insert id here
    String id = "id2";

    //define table by id
    WebElement tbl = driver.findElement(By.id("savings"));

    //get row count
    List<WebElement> rows = tbl.findElements(By.tagName("tr"));

    for(int i=0; i<rows.size(); i++) {
        List<WebElement> row = rows.get(i).findElements(By.tagName("td"));
        int columnCount = row.size();
        //check row contain td, not th
        if(columnCount > 0) {
            // 0=index id column from table with id 'savings'
            String getIDFromTable = row.get(0).getText();
            if(getIDFromTable.equals(id)){
                // 1=index balance column from table with id 'savings'
                String getBalance = row.get(1).getText();
                // 2=index available balance column from table with id 'savings'
                String getAvailableBalance = row.get(2).getText();
                System.out.println(getBalance);
                System.out.println(getAvailableBalance);
                break;
            }
        }
    }               
    driver.quit();

0
投票

建议使用xpath而不是获取列集合。这是代码。

public void getBalanceById(String id){
   String balance= driver.findElements(By.xpath("(//td[normalize-space(.)='" + id + ']/ancestor::tr/td)[last()-1]")).gettext();
}
© www.soinside.com 2019 - 2024. All rights reserved.