【问题标题】:Find largest image in a website using Puppeteer使用 Puppeteer 查找网站中最大的图像
【发布时间】:2019-02-11 20:58:25
【问题描述】:

我使用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));

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

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

【问题讨论】:

    标签: javascript node.js puppeteer cheerio


    【解决方案1】:

    您应该使用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());
    });
    

    【讨论】:

    • 这是一个服务器端代码。我无法在客户端内运行它
    • @GijoVarghese 你说你正在使用 puppeteer,你可以使用 evaluate 方法。我已经更新了代码。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多