首页 > 解决方案 > Puppeteer 如何将结果存储在对象变量中?

问题描述

如何将数据存储在对象变量中。我以为我熟悉对象变量,但我猜不是。我正在尝试像这样存储我的数据。

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

这是我目前拥有的代码。

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()
})();

我得到的结果是这样的。

{
  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',
  ]
}

如果你们中的任何人可以提供帮助,请提前感谢您。:) 这是我已经尝试过的一些事情。

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)}

以上所有这些都会出错并且不起作用。

标签: javascriptobjectpuppeteer

解决方案


你可以在你map()做类似的事情:

(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();
})();

推荐阅读