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

Gij*_*ese 4 javascript node.js cheerio 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));
Run Code Online (Sandbox Code Playgroud)

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

有没有办法使用Puppeteer找到网页中最大的图像而不需要这些技巧?由于浏览器正在渲染所有这些,因此它可以轻松找出哪一个是最大的

Gra*_*ler 5

您可以使用page.evaluate()在 Page DOM 上下文中执行 JavaScript,并将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);
Run Code Online (Sandbox Code Playgroud)