title: How to use cheerio to get the URL of an image on a given page for ALL cases
body: <p>right now I have a function that looks like this:</p>
  
  <pre><code>static getPageImg(url) {
      return new Promise((resolve, reject) =&gt; {
          //get our html
          axios.get(url)
          .then(resp =&gt; {
              //html
              const html = resp.data;
              //load into a $
              const $ = cheerio.load(html);
              //find ourself a img
              const src = url + "/" + $("body").find("img")[0].attribs.src;
              //make sure there are no extra slashes
              resolve(src.replace(/([^:]\/)\/+/g, "$1"));
          })
          .catch(err =&gt; {
             reject(err);
          });
      });
  }
  </code></pre>
  
  <p>this will handle the average case where the page uses a relative path to link to an image, and the host name is the same as the URL provided.</p>
  
  <p>However,
  most of the time the URL scheme will be more complex, like for example the URL might be stackoverflow.com/something/asdasd and what I need is to get stackoverflow.com/someimage link. Or the more interesting case where a CDN is used and the images come from a separate server. For example if I want to link to something from imgur ill give a link like : <a href="https://imgur.com/gallery/epqDj" rel="nofollow noreferrer">http://imgur.com/gallery/epqDj</a>. But the actual location of the image is at <a href="https://i.imgur.com/pK0thAm.jpg" rel="nofollow noreferrer">http://i.imgur.com/pK0thAm.jpg</a> a subdomain of the website. More interesting is the fact that if i was to get the src attribute I would have: "//i.imgur.com/pK0thAm.jpg".</p>
  
  <p>Now I imagine there must be a simple way to get this image, as the browser can very quickly and easily do a "open window in new tab" so I am wondering if anyone knows an easy way to do this other than writing a big function that can handle all these cases.</p>
  
  <p>Thank you!</p>