How to loop through an array?


#1

Hi all,

I am new to Apify and I am crawling Sainsbury’s, this is my start URL

I am looking to have the category, subcategory and subsubcategory display with every single items price, title and image src on the page.

I was able to return the category, subcategory and subsubcategory once and every items price, title and image src. This only works for the first item on every page.

function pageFunction(context) {
// called on every page the crawler visits, use it to extract data from it
var = context.jQuery; var result = []; (".article").each( function() {
result.push({

        title : $(this).find(".productNameAndPromotions:eq(0) a:eq(0)").text(),
        price : $(this).find(".pricePerUnit:eq(0)").text(),
        image : $(this).find('img').attr('src'),
        
        category : $(this).find('span:eq(1)').text(),
        subcategory : $(this).find('span:eq(3)').text(),
        subsubcategory : $(this).find('span:eq(5)').text(),
        subsubsubcategory : $(this).find('span:eq(7)').text()
     
   });
  });
return result;
}

This is what my code returns

How can I do this?


#2

Here is a script I used for another site, that might help you get started.

function pageFunction(context) {
     var result = [];
    $(".gridItem").each(function() {
            result.push({
                name: $(this).find(".productNameAndPromotions h3 a").text().trim(),
                price: $(this).find(".pricePerUnit").text().trim()
            });
        });
     if ($('li.next').length) {
           context.enqueuePage($('li.next > a').attr('href'));
       };
    return result;
}

#3

Solved!

`function pageFunction(context) {
// called on every page the crawler visits, use it to extract data from it
var $ = context.jQuery; 
var result = []; 

var _category = $(".article").find('span:eq(1)').text();
var _subcategory = $(".article").find('span:eq(3)').text();
var _subsubcategory = $(".article").find('span:eq(5)').text();
var _subsubsubcategory = $(".article").find('span:eq(7)').text();


$(".gridItem").each( function() {
    
result.push({
        
        title : $(this).find(".productNameAndPromotions:eq(0) a:eq(0)").text(),
        price : $(this).find(".pricePerUnit:eq(0)").text(),
        image : $(this).find('img').attr('src'),
        
        category : $.trim(_category),
        subcategory : $.trim(_subcategory),
        subsubcategory : $.trim(_subsubcategory),
        subsubsubcategory : $.trim(_subsubsubcategory),
     
   });
    
});

return result;

}`