如何用TestCafe的Selector存储页面元素到数组及定位重复属性元素
TestCafe元素数组存储与重复属性元素定位问题解答
一、能否通过Selector将HTML元素存入数组?
可以,但要注意TestCafe的Selector本质是异步查询对象,而非直接的DOM元素实例。你的代码存在两个关键问题:
numElements = Selector('button').filterVisible().count中count是Promise,必须通过await获取实际数值,否则循环不会执行;- 直接用
eql比较两个Selector对象没有意义,需要断言元素的具体属性(如文本、ID等)。
修正后的示例代码:
test('sample', async t => { // 先await获取实际元素数量 const numElements = await Selector('button').filterVisible().count; const elements = []; for (let i = 0; i < numElements; i++) { elements.push(Selector('button').filterVisible().nth(i)); } // 断言元素文本相等,需await获取文本值 const secondBtnText = await Selector('button').withText('Second').textContent; const arraySecondBtnText = await elements[1].textContent; await t.expect(arraySecondBtnText).eql(secondBtnText); });
如果想直接存储元素的属性值(而非Selector对象),可以一次性获取所有属性存入数组:
test('store button texts in array', async t => { const buttonSelector = Selector('button').filterVisible(); const count = await buttonSelector.count; const buttonTexts = []; for (let i = 0; i < count; i++) { buttonTexts.push(await buttonSelector.nth(i).textContent); } // 直接使用数组中的文本值 await t.expect(buttonTexts[1]).eql('Second'); });
二、如何访问aria-label相同的第二个元素?
nth()函数完全可以解决这个场景,问题出在Selector的链式调用顺序:先筛选出所有aria-label匹配的元素,再用nth定位索引,而非先取nth再筛选。
示例代码:
// 定位aria-label为"相同标签"的第二个元素 const secondSameLabelElement = Selector('input') .filter('[aria-label="相同标签"]') .nth(1); // TestCafe索引从0开始,第二个元素用1 // 操作该元素 await t.click(secondSameLabelElement);
如果你的nth()没生效,检查是否是以下原因:
- 筛选条件写在
nth()之后,导致先取第N个元素再筛选,结果为空; - 页面元素是动态加载的,需要添加等待或使用
with({ visibilityCheck: true })确保元素可见。
内容的提问来源于stack exchange,提问作者Andrew Wa
相关产品推荐
相关产品推荐

