Playwright/TypeScript:无法从表格中获取单元格数据求助
解决方案
核心原因
input 元素的显示内容存储在 value 属性中,而非元素的 textContent 或 innerHTML 里——这就是你用后两种方法拿不到数据的根本原因。
具体实现代码
以下是基于 Playwright/TypeScript 的完整实现,遍历表格所有行,分别提取第一个 div 单元格文本和其余 input 单元格的值:
import { test, Page } from '@playwright/test'; test('extract table row data', async ({ page }) => { await page.goto('你的页面URL'); // 定位表格所有行 const rows = page.locator('table tr'); const totalRows = await rows.count(); const allRowData: string[][] = []; for (let i = 0; i < totalRows; i++) { const currentRow = rows.nth(i); // 获取第一个div单元格的文本 const firstCellText = await currentRow.locator('td:first-child div').innerText(); // 获取剩余列的input元素 const inputCells = currentRow.locator('td:not(:first-child) input'); const inputCount = await inputCells.count(); const inputValues: string[] = []; for (let j = 0; j < inputCount; j++) { // 方法1:使用Playwright内置的inputValue()方法(推荐) const value = await inputCells.nth(j).inputValue(); // 方法2:如果inputValue不生效,通过evaluate直接读取DOM元素的value属性 // const value = await inputCells.nth(j).evaluate(el => (el as HTMLInputElement).value); inputValues.push(value); } // 组合整行数据并存入数组 allRowData.push([firstCellText, ...inputValues]); } // 输出结果 console.log('表格所有行数据:', allRowData); });
关键说明
- 定位 input 时无需依赖
tabindex,通过td:not(:first-child) input即可精准选中每行除第一列外的所有 input 元素。 inputValue()是 Playwright 专门为输入框提供的方法,能直接获取输入框的当前值,比手动读取value属性更可靠。- 如果遇到特殊类型的 input(如单选框、复选框),可以调整逻辑:比如复选框用
isChecked()获取选中状态,单选框用inputValue()获取选中值。
内容的提问来源于stack exchange,提问作者Raghavendra
相关产品推荐
相关产品推荐

