操纵Select的人具有相同选择器的元素列表

Huc*_*nan 6 javascript node.js google-chrome-devtools puppeteer

背景:

使用NodeJS / CucumberJS / Puppeteer构建emberJS解决方案的端到端回归测试。

问题:

当多个动态元素具有相同的选择器时,选择(page.click)并获取元素之一的textContent?(就我而言,我有4个具有相同选择器的元素= [data-test-foo4 =“ true”])

我知道,

const text = await page.evaluate( () => document.querySelector('[data-test-foo4="true"]').textContent );
Run Code Online (Sandbox Code Playgroud)

我可以获取第一个元素的文本,但是如何使用相同的选择器选择其他元素?我试过了:

var text = await page.evaluate( () => document.querySelectorAll('[data-test-foo4="true"]').textContent )[1];
console.log('text = ' + text);
Run Code Online (Sandbox Code Playgroud)

但这给了我'文字=未定义'

另外,以下内容:

await page.click('[data-test-foo4="true"]');
Run Code Online (Sandbox Code Playgroud)

使用该选择器选择第一个元素,但是如何使用该选择器选择下一个?

Gra*_*ler 11

您可以Array.from()用来创建一个包含textContent与选择器匹配的每个元素的所有值的数组:

const text = await page.evaluate(() => Array.from(document.querySelectorAll('[data-test-foo4="true"]'), element => element.textContent));

console.log(text[0]);
console.log(text[1]);
console.log(text[2]);
Run Code Online (Sandbox Code Playgroud)

如果您需要单击多个包含给定选择器的元素,则可以ElementHandle使用创建一个数组page.$$(),然后使用来单击每个数组elementHandle.click()

const example = await page.$$('[data-test-foo4="true"]');

await example[0].click();
await example[1].click();
await example[2].click();
Run Code Online (Sandbox Code Playgroud)


小智 6

https://github.com/puppeteer/puppeteer/blob/v5.5.0/docs/api.md#frameselector-1

const pageFrame = page.mainFrame();
const elems = await pageFrame.$$(selector);
Run Code Online (Sandbox Code Playgroud)