0

I am using cheerio to try and traverse the HTML of a website and I am trying grab the src attribute from the images but they are nested inside tags. I have tried a few solutions one example given below but no luck. Thank you in advance. enter image description here

 const snkrsproduct = $('a.card-link img');
        const snkrsImg = snkrsproduct.attr('src');
        console.log(snkrsImg);

It keeps returning undefined. My logic to this is that I am grabbing the a tag with a class of card-link and then the img and assigning that img src value to snkrsImg but obviously I am missing something.

Ksuby
  • 73
  • 3
  • 10
  • Have you tried using a selector like 'a.card-link>img' – Sage Jun 15 '19 at 13:53
  • I'll give that try but how does that differ from "a.card-link img" ? – Ksuby Jun 15 '19 at 13:58
  • The > in a selector says 'is child of'. So, in this case, it says: img is child of a.card-link – Sage Jun 15 '19 at 14:05
  • const snkrsproduct = $('.card-link > img'); still comes back undefined , not sure why – Ksuby Jun 15 '19 at 14:07
  • Him. Yeah, I've had problems with cheerio and selecting elements. Your positive that the a has a class of 'card-link'? – Sage Jun 15 '19 at 14:09
  • Just saw the image you attached. Looks like it should work. Do any selectors work? – Sage Jun 15 '19 at 14:10
  • Next thing I would try is $('a.card-link') and see if that comes back with a collection that you can iterate. From there, you should be able to get to the child elements and grab the src attribute. If $('a.card-link') does NOT work, then cheerio might be having a problem with the fact that the a element has multiple classes on it. – Sage Jun 15 '19 at 14:19
  • Yeah I can grab the .card-link and get the data off of that such as 'href' and 'aria-label' – Ksuby Jun 15 '19 at 14:20
  • Yes no $('a.card-link').attr(aria-label) returns the name of the shoe , so that is working. but i dont understand why it can go one level down and grab the img hahaha – Ksuby Jun 15 '19 at 14:21
  • does this answer help? https://stackoverflow.com/a/41198485/462121 – Sage Jun 15 '19 at 14:22
  • No , that didn't work either I tried this const snkrimgUrl = $('img[class="image-component"]'); – Ksuby Jun 15 '19 at 14:30
  • what about this: $('a.card-link').siblings('img') – Sage Jun 15 '19 at 14:34
  • actually, it should have been this one: $('a.card-link').children('img') – Sage Jun 15 '19 at 15:27
  • Sorry , had to go to work :/ gonna give this a shot – Ksuby Jun 15 '19 at 20:18
  • It sounds like it's not there. Just because it's in the inspector doesn't mean it's in the html. You might need puppeteer for this. – pguardiario Jun 16 '19 at 00:08
  • Yeah , fellow dev mentioned this to me. The pages are being rendered using react and possibly redux. – Ksuby Jun 16 '19 at 02:14

0 Answers0