使用Cucumber+Webdriver.io+JS选取表格首行第三元素报错求助
问题与解决方案:Webdriver.io定位表格元素失败
问题描述
使用Cucumber、Webdriver.io和JavaScript,需要选取页面表格首行的第三个元素。表格ID会变化,但始终以__table开头,页面仅存在一个表格。尝试两段代码均报错:
- 第一段用for循环遍历表格,但循环内代码未执行;
- 第二段去掉循环后,出现
TypeError: Cannot read properties of undefined (reading '$')错误。
尝试的代码及报错
尝试代码1
When("the user selects the customer from the results", async function () { // Implementation for selecting the customer from the results const tables = await $$('table[id^="__tables"]'); console.log('Tables:', tables); for (const table of tables) { // Your code to interact with each table const firstRow = await table.$('tr'); const thirdCell = await firstRow.$$('td')[2]; // Index 2 for the third cell const text = await thirdCell.getText(); console.log('Cell text', text); await thirdCell.waitForClickable(); await thirdCell.click() } });
尝试代码2
When("the user selects the customer from the results", async function () { // Implementation for selecting the customer from the results const tables = await $$('table[id^="__tables"]'); console.log('Tables:', tables); // Assuming you want to interact with the first table found const targetTable = tables[0]; // Locate the first row in the table const firstRow = await targetTable.$('tr'); // Locate the third cell (td) in the first row const thirdCell = await firstRow.$$('td')[2]; // Index 2 for the third cell // Perform actions on the selected cell await thirdCell.click(); });
对应报错
[0-0] Error in "0: And the user selects the customer from the results" TypeError: Cannot read properties of undefined (reading '$')
解决方案
报错原因
- 选择器拼写错误:要匹配ID以
__table开头的表格,但代码里写的是__tables(多了一个s),导致$$方法找不到任何元素,tables为空数组。循环自然不会执行,取tables[0]得到undefined,调用其$方法就会触发报错。 - Promise处理错误:
firstRow.$$('td')返回的是Promise,不能直接在后面加[2]取索引,必须先await获取数组后再取值。
修正后的代码
When("the user selects the customer from the results", async function () { // 修正选择器:匹配以__table开头的ID const tables = await $$('table[id^="__table"]'); // 先确认表格存在,避免后续操作报错 if (!tables.length) { throw new Error("未找到目标表格"); } const targetTable = tables[0]; // 定位表格首行:加上tbody避免误选表头的tr(可选但推荐) const firstRow = await targetTable.$('tbody tr'); // 先await获取所有单元格,再取第三个元素(索引为2) const cells = await firstRow.$$('td'); if (cells.length < 3) { throw new Error("表格首行不足3个单元格"); } const thirdCell = cells[2]; // 等待元素可点击后再执行点击 await thirdCell.waitForClickable(); await thirdCell.click(); });
关键修正点
- 修正CSS选择器的拼写错误,确保能匹配到目标表格;
- 增加元素存在性判断,抛出明确的错误信息,便于调试;
- 正确处理
$$返回的Promise:先await获取数组,再通过索引访问元素; - 可选优化:定位行时指定
tbody,避免误选表头的tr元素(如果页面表格包含<thead>标签)。
内容的提问来源于stack exchange,提问作者Ade Teriba
相关产品推荐
相关产品推荐

