You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Puppeteer如何从匹配到的第一个元素中获取子元素数组?

实现方案

可以通过**$eval先定位到第一个class为test的figure元素,再在该元素的上下文内用$$eval**获取所有子div元素并提取内容数组,具体代码如下:

// 以支持$eval/$$eval的环境(如Puppeteer)为例
const divContents = await page.$eval('figure.test:first-of-type', (figure) => {
  return Array.from(figure.querySelectorAll('div')).map(div => div.textContent.trim());
});

代码说明

  • $eval('figure.test:first-of-type', ...):匹配并获取第一个class为test的figure元素,将其作为回调函数的参数传入
  • 回调函数内,通过figure.querySelectorAll('div')获取该figure下的所有div元素,转成数组后用map提取每个div的文本内容(trim()用于清除文本两端多余空格)

如果环境不支持:first-of-type选择器,也可以直接依赖$eval只返回第一个匹配元素的特性,简化选择器:

const divContents = await page.$eval('figure.test', (figure) => {
  return Array.from(figure.querySelectorAll('div')).map(div => div.textContent.trim());
});

内容的提问来源于stack exchange,提问作者glpsx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:24:20