嵌套的 div 和 table 元素在 playwright 中不返回值

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

我正在与 Playwright 合作,想要捕获嵌套元素并将值放入数组中。

在我的代码中尝试这样的事情:

await test.step('Extract table data from HTML', async () => {
    const targetContainer = await page.locator('.new-item-container[style="width: 4190px; transform: translate(0px, 0px);"]');
    await targetContainer.waitFor();

    const tableData = await targetContainer.evaluate(container => {
        const tables = container.querySelectorAll('table');
        const data = [];

        tables.forEach(table => {
            const rows = table.querySelectorAll('tbody > tr');
            const rowData = [];

            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                const cellData = [];

                cells.forEach(cell => {
                    cellData.push(cell.innerText.trim());
                });

                rowData.push(cellData);
            });

            data.push(rowData);
        });

尝试直接在浏览器中执行此操作,我可以毫无问题地捕获它们,但仍难以使其在 Playwright 中工作。

typescript playwright playwright-typescript
1个回答
0
投票

您没有在评估函数中返回任何数据,可能是尝试以下代码的问题。

await test.step('Extract table data from HTML', async () => {
const targetContainer = await page.locator('.new-item-container[style="width: 4190px; transform: translate(0px, 0px);"]');
await targetContainer.waitFor();

const tableData = await targetContainer.evaluate(container => {
    const tables = container.querySelectorAll('table');
    const data = [];

    tables.forEach(table => {
        const rows = table.querySelectorAll('tbody > tr');
        const rowData = [];

        rows.forEach(row => {
            const cells = row.querySelectorAll('td');
            const cellData = [];

            cells.forEach(cell => {
                cellData.push(cell.textContent.trim());
            });

            rowData.push(cellData);
        });

        data.push(rowData);
    });

    return data;
});

});

© www.soinside.com 2019 - 2024. All rights reserved.