Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cheerio Get Image Src With No Class

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
like image 911
Alteredorange Avatar asked Nov 28 '17 22:11

Alteredorange


2 Answers

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');
like image 128
tosi Avatar answered Nov 02 '22 20:11

tosi


The thing you have to do is to check the DOM with:

console.log(.container_c89a5 .lazyLoadContainer_b1038)

after that you see the DOM json format. You can choose img by this kind of way:

console.log(.container_c89a5 .lazyLoadContainer_b1038).next()) or .children())

After that you will see the DOM and all the new thing and you can have access with a .data or .src, just check the DOM with console.log

like image 1
Ke Vin Avatar answered Nov 02 '22 21:11

Ke Vin