Puppeteer 阵列 returns 只有 null

Puppeteer Array returns only null

我想将所有 img 从选择器传递到 imgs,然后将 imgs 的高度推入一个数组。

现在我得到一个数组,每个 img returns 为 null。 使用普通的 Js 没问题,但现在我尝试让它与 puppeteer 一起工作。

await page.waitForSelector(".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");
   heights = [];

  imgs = await page.$$(".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");

  for(let i = 0; i < imgs.length; i++){
    heights.push(imgs[i].height);
    }

    await page.evaluate(({heights}) => {
      console.log(heights);
  },{heights});

我希望得到一个包含每个 img 高度的数组。

我实际上从每个 img 中得到一个带有 null 的数组。

imgs 不会是 DOM 元素的数组,而是 Puppeteer ElementHandles。它可以定义为 "DOM pointers"。这意味着 ElementHandle 不会有 height 属性.

如果你想获得高度,你可以使用 $$eval

const heights = await page.$$eval(
    ".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top", 
    imgs => imgs.map(i => i.height));

第二个参数将是一个函数,需要匹配该选择器的图像列表。从那里你可以简单地遍历它们。

您也可以将其一分为二:

const imgs = await page.$$eval(
    ".content-filter.teaser-slider.rondell-section.slides_2 .teaserBorderWrapper .autoTeaserImageWrapper.paddingBottom_twoThird .card-img-top");
const heights = page.eval(imgs => imgs.map(i => i.height), imgs);