Google Puppeteer forEach不是一个功能

时间:2018-04-09 10:34:51

标签: javascript node.js puppeteer

我有以下功能:

    (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('http://elgiganten.dk');
    await page.setViewport({width: 1920, height: 1200});
    await page.type('#main-search', 'El');
    await page.keyboard.press('Enter');
    await page.waitForSelector('#no-products');
    //await page.screenshot({path: 'view.png'});

    // execute standard javascript in the context of the page.
    await page.addScriptTag({url: 'https://code.jquery.com/jquery-3.2.1.min.js'});
    const foundProducts = await page.evaluate(() => {
        var products = $('.mini-product-content');
        var returnArray = [];

        products.forEach(function (product) {
            var container = product.find('a');
            returnArray.push({
                title: container.title
            });
        });


        return products;
    });
    console.log(foundProducts);
    await browser.close();
})();

课程'.mini-product-content'在网页上存在14次。现在,你可以看到我试图循环它们,但每当我这样做时,我得到以下错误:

  

错误:评估失败:TypeError:products.forEach不是函数

如果我删除它而不是打印出结果我得到以下内容:

    { '0': {},
  '1': {},
  '2': {},
  '3': {},
  '4': {},
  '5': {},
  '6': {},
  '7': {},
  '8': {},
  '9': {},
  '10': {},
  '11': {},
  '12': {},
  '13': {},
  length: 14,
  prevObject: 
   { '0': 
      { location: [Object],
        __satellite__: 2,
        SearchForm: [Object],
        StoreForm: [Object],
        _html5shiv: 1,
        jQuery2240488744717004840461: [Object] },
     length: 1 } }

以上是使用console.log

所以我的问题是我做错了什么?

1 个答案:

答案 0 :(得分:1)

您正在尝试迭代jQuery列表。您应该将.forEach()替换为jQuery equivalent .each()