Cheerio Get Image Src With No Class

Alteredorange picture Alteredorange · Nov 28, 2017 · Viewed 9.5k times · Source

Trying to pull the img source with Cheerio, but the img doesn't have a class. It looks like

<div class="container_c89a5 lazyLoadContainer_b1038">
<img height="80" src="https://stuff.com" srcset="https://stuff.com" width="80">
</div>

I've tried selecting the image source a couple different ways with no luck.

var $ = cheerio.load(html);
    $('div.item_54fdd').each(function(i, element) {
        var a = $(this);
        var title = a.find('.title_9ddaf').text(); //works great
        var image = a.find('div.container_c89a5').first('img').attr('src');  //no luck
        var image = a.find('div.container_c89a5 > img').attr('src');  //no luck

Answer

tosi picture tosi · Nov 29, 2017

Have you tried using find()? This works for me:

a.find('.container_c89a5').find('img').attr('src');

Selecting first img tag via index using eq(i)

a.find('.container_c89a5').children('img').eq(0).attr('src');