Neik0
Neik0

Reputation: 103

Puppeteer how to store results in an object variable?

How do I store data in an object variable. I thought I was familiar with object variables but I guess not. I am trying to store my data like this.

Product:{
   Title: Bla Bla Bla
}
Product:{
   Title: Ala Ala Ala
}

Here is the code I currently have.

const puppeteer = require('puppeteer');

(async () => {
    let movieURL = 'https://www.walmart.com/search/?query=&cat_id=91083';

    let productName = []
    let browser = await puppeteer.launch({ headless: true});
    let page = await browser.newPage();

    await page.goto(movieURL, {waitUntil: 'networkidle2'});

     let data = await page.evaluate(() => {
        productName = [...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)

        return{
            productName
        }
    })

    console.log(data);

    await browser.close()
})();

The results I get are like this.

{
  productName: [
    'SQ Non Chlorinated Brake Parts Cleaner',
    'Super Tech DEF Diesel Exhaust Fluid, 2.5 Gallon',
    'Mobil 1 Advanced Fuel Economy Full Synthetic Motor O ...\n',
  ]
}

Thank you in advance if you any of you guys or girls can help. :) Here are some things I have already tried.

productName += [...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)
productName[data] = {[...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)}
productName = {[...document.querySelectorAll('a.product-title-link')].map(a => a.innerText)}

All of those above give errors and do not work.

Upvotes: 1

Views: 597

Answers (1)

Luís Ramalho
Luís Ramalho

Reputation: 10218

You can in your map() do something like:

(a) => ({ Product: { Title: a.innerText } })

const puppeteer = require("puppeteer");

(async () => {
  let movieURL = "https://www.walmart.com/search/?query=&cat_id=91083";

  let productName = [];
  let browser = await puppeteer.launch({ headless: true });
  let page = await browser.newPage();

  await page.goto(movieURL, { waitUntil: "networkidle2" });

  let data = await page.evaluate(() => {
    productName = [
      ...document.querySelectorAll("a.product-title-link"),
    ].map((a) => ({ Product: { Title: a.innerText } }));

    return {
      productName,
    };
  });

  console.log(data);

  await browser.close();
})();

Upvotes: 1

Related Questions