Javascript Puppeteer 使用相同的选择器获取元素列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52224816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:57:09  来源:igfitidea点击:

Puppeteer Getting List of Elements with Same Selector

javascriptnode.jsgoogle-chrome-devtoolspuppeteer

提问by Huckleberry Carignan

Background:

背景:

Using NodeJS/CucumberJS/Puppeteer to build end-to-end regression test for an emberJS solution.

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

Problem:

问题:

Selecting (page.click) and getting textContent of one of the elements when there are several dynamic elements with the same selector? (In my case, I have 4 elements with the same selector = [data-test-foo4="true"])

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

I know, that with:

我知道,与:

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

I can get the text of the first element, but how do I select the other elements with the same selector? I've tried:

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

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

but it gives me 'text = undefined'

但它给了我 'text = undefined'

Also, the following:

此外,以下内容:

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

selects the first elements with that selector, but how can I select the next one with that selector?

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

回答by Grant Miller

You can use Array.from()to create an array containing all of the textContentvalues of each element matching your selector:

您可以使用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]);

If you need to click more than one element containing a given selector, you can create an ElementHandlearray using page.$$()and click each one using elementHandle.click():

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

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

await example[0].click();
await example[1].click();
await example[2].click();