Iterate through HTML rows and columns of a table u

2019-07-25 12:21发布

问题:

I want to iterate through rows and columns using Selenium Webdriver (I am using Protractor for non-angular web page). I get number of links for doing this using JAVA code which uses WebElement class. However, I need to do this using JavaScript code.

Thanks, Sakshi

回答1:

The following worked:

browser.driver.findElement(by.id('table_id')).then(function(table){
    table.findElement(by.tagName('tbody')).then(function(tbody){
        tbody.findElements(by.tagName('tr')).then(function(rows){
            for(i=0; i<rows.length;i++)
            {
                rows[i].findElements(by.tagName('td')).then(function(cols){
                    expect(cols[2].getText()).toMatch('ok');
                });

            }

        });
    });
});

Thanks, Sakshi



回答2:

var testData = [
    ['row 0, cell 0', 'row 0, cell 1', 'row 0, cell 2'],
    ['row 1, cell 0', 'row 1, cell 1', 'row 1, cell 2'],
    ['row 2, cell 0', 'row 2, cell 1', 'row 2, cell 2'],
];

// Traverse rows
$$('tr').each(function(rowElm, r) {
    // Traverse cols
    rowElm.$$('td').each(function(cellElm, c) {
        // Workout cell
        expect(cellElm.getText()).toContain(testData[r][c]);
    });
});


回答3:

The simplest way is to use xpath

browser.driver.findElement(by.xpath("//table[@id='table_id']/tbody//tr")).then(function(rows){
  //your code...
  for(i=0; i<rows.length;i++){
    rows[i].findElements(by.tagName('td')).then(function(cols){
       expect(cols[2].getText()).toMatch('ok');
    });
  }
})