代码之家  ›  专栏  ›  技术社区  ›  Gijo Varghese

在一个网站上找到最大的图像使用木偶

  •  1
  • Gijo Varghese  · 技术社区  · 6 年前

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

    但是,只有在img的with width是inline时,它才起作用。如果没有宽度,我会把它的宽度设为 -1 在分类时考虑

    有没有办法找到最大的图像在网页上没有这些黑客,使用

    2 回复  |  直到 6 年前
        1
  •  3
  •   Grant Miller    5 年前

    你可以用 page.evaluate() src 返回节点/木偶师的最大图像的属性:

    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);
    
        2
  •  2
  •   Ilia Choly    6 年前

    naturalWidth naturlaHeight

    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());
    });