I have the following code that attempts to scrape all the 'Add to basket' button elements from the page, put them in an array and return that array to the Node environment.
const puppeteer = require('puppeteer');
let getArrayofButtons = async () => {
const browser = await puppeteer.launch({
devtools: 'true',
});
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 1800 });
await page.goto('http://books.toscrape.com/', {
waitUntil: 'domcontentloaded',
});
await page.waitForSelector('.product_pod');
let buttons = [];
await page.evaluate(() => {
buttons = [...document.querySelectorAll('*')].filter(e =>
[...e.childNodes].find(n => n.nodeValue?.match('basket'))
);
console.log(buttons);
});
// browser.close();
};
getArrayofButtons().then(returnedButtons => {
console.log(returnedButtons);
});
When I console.log(buttons); I can see the array of button elements in the browser environment, but when I try to return that array to the Node environment I get undefined.
My understanding is that page.evaluate() will return the value of the function passed to it, so if I replace:
articles = [...document.querySelectorAll('*')].filter(e => [...e.childNodes].find(n => n.nodeValue?.match('basket')) );
with:
return [...document.querySelectorAll('*')].filter(e => [...e.childNodes].find(n => n.nodeValue?.match('basket')) );
it seems like it should work. Am I not resolving the Promise correctly?