使用 Puppeteer 在网站中查找最大的图像

Find largest image in a website using Puppeteer

我正在使用 Cheerio 来查找网页中最大的图像。这是我使用的代码:

  const { src } = $('img')
      .map((i, el) => ({
        src: el.attribs.src,
        width: el.attribs.width ? Number(el.attribs.width.match(/\d+/)[0]) : -1,
      }))
      .toArray()
      .reduce((prev, current) => (prev.width > current.width ? prev : current));

但是,只有当 width 是内联的 img 时,它才有效。如果没有宽度,我会将其宽度设置为 -1 并在排序时考虑它

有没有什么方法可以使用 Puppeteer 在没有这些技巧的情况下找到网页中最大的图像?由于浏览器正在渲染所有这些,它可以很容易地找出哪个是最大的

您应该使用 naturalWidthnaturlaHeight 属性。

const image = await page.evaluate(() => {

  function size(img) {
    if (!img) {
      return 0;
    }
    return img.naturalWith * img.naturalHeight;
  }

  function info(img) {
    if (!img) {
      return null;
    }
    return {
      src:  img.src,
      size: size(img)
    }
  }

  function largest() {
    let best = null;
    let images = document.getElementsByTagName("img");
    for (let img of images) {
      if (size(img) > size(best)) {
        best = img
      }
    }
    return best;
  }

  return info(largest());
});

可以使用page.evaluate()在PageDOM上下文中执行JavaScript,return最大图片的src属性返回Node/Puppeteer:

const largest_image = await page.evaluate(() => {
  return [...document.getElementsByTagName('img')].sort((a, b) => b.naturalWidth * b.naturalHeight - a.naturalWidth * a.naturalHeight)[0].src;
});

console.log(largest_image);