【发布时间】:2018-04-09 20:34:17
【问题描述】:
我有以下功能:
(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
所以我的问题是我做错了什么?
【问题讨论】:
-
尝试改用
for of.. 例如。for (const product of products) {products 很可能是可迭代的,但不是数组。
标签: javascript node.js puppeteer