Search code examples
javascriptexpresscheerioscraper

Cheerio can't find IMG src


My cheerio code doesn't seem to be working. I'm trying to get the src from the <img> tag found inside of the imgWrap div at the given link.

I've tried rewriting .imgWrap as .imgWrap img and removing the find but that didn't work either...

However, if i do $(element).children() or $(element).html() I see the results I expect to...

request.get('http://www.bk.com/menu/burgers', function(error, response, body) {
   const $ = cheerio.load(body);

   let menu = $('.imgWrap').each(function(i, element) {
      let thing = $(element).find('img').attr('src');
      console.log(thing);
   });
})

Solution

  • Turns out this specific website uses lazy-loading to load their images, so the view source upon inspecting is actually different than the information received in the get request.

    the get request does not have an src associated with the img element, but rather a data-cfsrc which is holding the same information as the src in the view source.

    so, the line should actually be this:

    let thing = $(element).find('img').attr('data-cfsrc');
    

    Thanks big time to @rlemon for the help in troubleshooting this!