Get specific cell value from Playwright typescript

506 views Asked by At

I have a table with n columns and rows. Would like to fetch "Column X" value whose "Name" is "Ram" through playwright Example Table

I have tried through Iteration but didnt work (All my headers are in table1 and body content in table2)

let columns = await this.page.locator("//th[@role='columnheader']").count();
for (var i = 0; i < await columns; i++) {
        //getting the column header
        let val = await this.page.locator("//th[@role='columnheader']//span[contains(@class,'mat-tooltip-trigger')]").nth(i).innerText()

    //When column header equal to expected header, fetching the cell value of row-1
    if (val == value) {
      return await this.page.locator("//table//tbody//tr[1]//td").nth(i);
      break
    }``
 
2

There are 2 answers

1
Zeeshan Asghar On

You can get and assert the specific cell value in this way.

const tableSelector = 'table#yourTableID'; // provide CSS selector of your table

// Replace with the row and column indices you want (both are 0-based).

const rowIndex = 2; const columnIndex = 1;

// Locate the table and cell using Playwright functions.

const table = await page.$(tableSelector);

const cell = await table.$(tr:nth-child(${rowIndex}) td:nth-child(${columnIndex}));

// Assert that the cell exists.

await expect(cell).not.toBeNull();

// Extract and assert the cell content.

const cellValue = await cell.textContent(); await expect(cellValue).toBe('Expected Cell Value');

0
Vishal Aggarwal On

We can find the specific row based on name text as "Ram" and as column number will be static we can just pass the actual column number :

await this.page.locator('//table//tbody//tr[contains(.,"Ram")]//td').nth(staticColNum)